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

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

Introduction

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

Prototype

public static <T extends CharSequence> T defaultIfBlank(final T str, final T defaultStr) 

Source Link

Document

Returns either the passed in CharSequence, or if the CharSequence is whitespace, empty ("") or null , the value of defaultStr .

 StringUtils.defaultIfBlank(null, "NULL")  = "NULL" StringUtils.defaultIfBlank("", "NULL")    = "NULL" StringUtils.defaultIfBlank(" ", "NULL")   = "NULL" StringUtils.defaultIfBlank("bat", "NULL") = "bat" StringUtils.defaultIfBlank("", null)      = null 

Usage

From source file:cgeo.geocaching.cgeocaches.java

@Override
public void onCreateContextMenu(final ContextMenu menu, final View view,
        final ContextMenu.ContextMenuInfo info) {
    super.onCreateContextMenu(menu, view, info);

    AdapterContextMenuInfo adapterInfo = null;
    try {// ww  w .jav  a  2s. c om
        adapterInfo = (AdapterContextMenuInfo) info;
    } catch (Exception e) {
        Log.w("cgeocaches.onCreateContextMenu", e);
    }

    if (adapterInfo == null || adapterInfo.position >= adapter.getCount()) {
        return;
    }
    final Geocache cache = adapter.getItem(adapterInfo.position);

    menu.setHeaderTitle(StringUtils.defaultIfBlank(cache.getName(), cache.getGeocode()));

    contextMenuGeocode = cache.getGeocode();

    if (cache.getCoords() != null) {
        menu.add(0, MENU_DEFAULT_NAVIGATION, 0,
                NavigationAppFactory.getDefaultNavigationApplication().getName());
        menu.add(1, MENU_NAVIGATION, 0, res.getString(R.string.cache_menu_navigate))
                .setIcon(R.drawable.ic_menu_mapmode);
        LoggingUI.addMenuItems(this, menu, cache);
        menu.add(0, MENU_CACHE_DETAILS, 0, res.getString(R.string.cache_menu_details));
    }
    if (cache.isOffline()) {
        menu.add(0, MENU_DROP_CACHE, 0, res.getString(R.string.cache_offline_drop));
        menu.add(0, MENU_MOVE_TO_LIST, 0, res.getString(R.string.cache_menu_move_list));
        menu.add(0, MENU_EXPORT, 0, res.getString(R.string.export));
        menu.add(0, MENU_REFRESH, 0, res.getString(R.string.cache_menu_refresh));
    } else {
        menu.add(0, MENU_STORE_CACHE, 0, res.getString(R.string.cache_offline_store));
    }
}

From source file:nl.b3p.viewer.config.services.ArcGISService.java

private Layer parseArcGISLayer(JSONObject agsl, GeoService service, ArcGISFeatureSource fs,
        Map<String, List<String>> childrenByLayerId) throws JSONException {
    Layer l = new Layer();
    // parent set later in 2nd pass
    l.setService(service);//w w w. j av a  2  s .c  o  m
    l.setName(agsl.getString("id"));
    l.setTitle(agsl.getString("name"));

    JSONArray subLayerIds = agsl.optJSONArray("subLayers");
    if (subLayerIds != null) {
        List<String> childrenIds = new ArrayList();
        for (int i = 0; i < subLayerIds.length(); i++) {
            JSONObject subLayer = subLayerIds.getJSONObject(i);
            String subLayerId = subLayer.getInt("id") + "";
            childrenIds.add(subLayerId);
        }
        childrenByLayerId.put(l.getName(), childrenIds);
    }

    l.getDetails().put(DETAIL_TYPE, new ClobElement(agsl.getString("type")));
    l.getDetails().put(DETAIL_CURRENT_VERSION,
            new ClobElement(agsl.optString("currentVersion", currentVersion)));
    l.getDetails().put(DETAIL_DESCRIPTION,
            new ClobElement(StringUtils.defaultIfBlank(agsl.getString("description"), null)));
    l.getDetails().put(DETAIL_GEOMETRY_TYPE, new ClobElement(agsl.getString("geometryType")));
    l.getDetails().put(DETAIL_CAPABILITIES, new ClobElement(agsl.optString("capabilities")));
    l.getDetails().put(DETAIL_DEFAULT_VISIBILITY,
            new ClobElement(agsl.optBoolean("defaultVisibility", false) ? "true" : "false"));
    l.getDetails().put(DETAIL_DEFINITION_EXPRESSION,
            new ClobElement(StringUtils.defaultIfBlank(agsl.optString("definitionExpression"), null)));

    removeEmptyMapValues(l.getDetails());

    try {
        l.setMinScale(agsl.getDouble("minScale"));
        l.setMaxScale(agsl.getDouble("maxScale"));
    } catch (JSONException e) {
    }

    try {
        JSONObject extent = agsl.getJSONObject("extent");
        BoundingBox bbox = new BoundingBox();
        bbox.setMinx(extent.getDouble("xmin"));
        bbox.setMaxx(extent.getDouble("xmax"));
        bbox.setMiny(extent.getDouble("ymin"));
        bbox.setMaxy(extent.getDouble("ymax"));
        bbox.setCrs(new CoordinateReferenceSystem(
                "EPSG:" + extent.getJSONObject("spatialReference").getInt("wkid")));
        l.getBoundingBoxes().put(bbox.getCrs(), bbox);
    } catch (JSONException e) {
    }

    // XXX implemented in ArcGISDataStore
    // XXX sometimes geometry field not in field list but layer has geometryType
    boolean hasFields = false;
    if (!agsl.isNull("fields")) {
        JSONArray fields = agsl.getJSONArray("fields");
        if (fields.length() > 0) {
            SimpleFeatureType sft = new SimpleFeatureType();
            sft.setFeatureSource(fs);
            sft.setTypeName(l.getName());
            sft.setDescription(l.getTitle());
            sft.setWriteable(false);

            for (int i = 0; i < fields.length(); i++) {
                JSONObject field = fields.getJSONObject(i);

                AttributeDescriptor att = new AttributeDescriptor();
                sft.getAttributes().add(att);
                att.setName(field.getString("name"));
                att.setAlias(field.getString("alias"));

                String et = field.getString("type");
                String type = AttributeDescriptor.TYPE_STRING;
                if ("esriFieldTypeOID".equals(et)) {
                    type = AttributeDescriptor.TYPE_INTEGER;
                } else if ("esriFieldTypeGeometry".equals(et)) {
                    if (sft.getGeometryAttribute() == null) {
                        sft.setGeometryAttribute(att.getName());
                    }
                    String gtype = agsl.getString("geometryType");
                    if ("esriGeometryPoint".equals(gtype)) {
                        type = AttributeDescriptor.TYPE_GEOMETRY_POINT;
                    } else if ("esriGeometryMultipoint".equals(gtype)) {
                        type = AttributeDescriptor.TYPE_GEOMETRY_MPOINT;
                    } else if ("esriGeometryLine".equals(gtype) || "esriGeometryPolyline".equals(gtype)) {
                        type = AttributeDescriptor.TYPE_GEOMETRY_LINESTRING;
                    } else if ("esriGeometryPolygon".equals(gtype)) {
                        type = AttributeDescriptor.TYPE_GEOMETRY_POLYGON;
                    } else {
                        // don't bother
                        type = AttributeDescriptor.TYPE_GEOMETRY;
                    }
                } else if ("esriFieldTypeDouble".equals(et)) {
                    type = AttributeDescriptor.TYPE_DOUBLE;
                } else if ("esriFieldTypeInteger".equals(et) || "esriFieldTypeSmallInteger".equals(et)) {
                    type = AttributeDescriptor.TYPE_INTEGER;
                } else if ("esriFieldTypeDate".equals(et)) {
                    type = AttributeDescriptor.TYPE_DATE;
                }
                att.setType(type);
            }
            fs.getFeatureTypes().add(sft);
            l.setFeatureType(sft);
            hasFields = true;
        }
    }

    /* We could check capabilities field for "Query", but don't bother,
     * group layers have Query in that property but no fields...
     */
    l.setQueryable(hasFields);
    l.setFilterable(hasFields);

    l.setVirtual(!NON_VIRTUAL_LAYER_TYPES.contains(l.getDetails().get(DETAIL_TYPE).getValue()));

    return l;
}

From source file:nl.b3p.viewer.stripes.EditFeatureActionBean.java

private String addNewFeature() throws Exception {

    SimpleFeature f = DataUtilities.template(store.getSchema());

    Transaction transaction = new DefaultTransaction("create");
    store.setTransaction(transaction);/*  w w w  . j av  a  2  s.  com*/

    for (AttributeDescriptor ad : store.getSchema().getAttributeDescriptors()) {
        if (ad.getType() instanceof GeometryType) {
            String wkt = jsonFeature.optString(ad.getLocalName(), null);
            Geometry g = null;
            if (wkt != null) {
                g = new WKTReader().read(wkt);
            }
            f.setDefaultGeometry(g);
        } else {
            String v = jsonFeature.optString(ad.getLocalName());
            f.setAttribute(ad.getLocalName(), StringUtils.defaultIfBlank(v, null));
        }
    }

    log.debug(String.format("Creating new feature in feature source source #%d: %s",
            layer.getFeatureType().getId(), f.toString()));

    try {
        List<FeatureId> ids = store.addFeatures(DataUtilities.collection(f));

        transaction.commit();
        return ids.get(0).getID();
    } catch (Exception e) {
        transaction.rollback();
        throw e;
    } finally {
        transaction.close();
    }
}

From source file:nl.b3p.viewer.stripes.EditFeatureActionBean.java

private void editFeature(String fid) throws Exception {
    Transaction transaction = new DefaultTransaction("edit");
    store.setTransaction(transaction);/*from w  w w  .  j  a v  a 2 s  . co m*/

    FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();
    Filter filter = ff.id(new FeatureIdImpl(fid));

    List<String> attributes = new ArrayList<String>();
    List values = new ArrayList();
    for (Iterator<String> it = jsonFeature.keys(); it.hasNext();) {
        String attribute = it.next();
        if (!FID.equals(attribute)) {

            AttributeDescriptor ad = store.getSchema().getDescriptor(attribute);

            if (ad != null) {
                attributes.add(attribute);

                if (ad.getType() instanceof GeometryType) {
                    String wkt = jsonFeature.getString(ad.getLocalName());
                    Geometry g = null;
                    if (wkt != null) {
                        g = new WKTReader().read(wkt);
                    }
                    values.add(g);
                } else {
                    String v = jsonFeature.getString(attribute);
                    values.add(StringUtils.defaultIfBlank(v, null));
                }
            } else {
                log.warn(String.format("Attribute \"%s\" not in feature type; ignoring", attribute));
            }
        }
    }

    log.debug(String.format("Modifying feature source #%d fid=%s, attributes=%s, values=%s",
            layer.getFeatureType().getId(), fid, attributes.toString(), values.toString()));

    try {
        store.modifyFeatures(attributes.toArray(new String[] {}), values.toArray(), filter);

        transaction.commit();
    } catch (Exception e) {
        transaction.rollback();
        throw e;
    } finally {
        transaction.close();
    }
}

From source file:nl.b3p.viewer.stripes.IbisEditFeatureActionBean.java

/**
 * Override the method from the base class to process our workflow.
 *
 * @param fid//  w w w . j  a v  a 2  s  . c  o  m
 * @throws Exception
 */
@Override
protected void editFeature(String fid) throws Exception {
    log.debug("ibis editFeature:" + fid);
    FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2();
    Filter fidFilter = ff.id(new FeatureIdImpl(fid));

    List<String> attributes = new ArrayList();
    List values = new ArrayList();
    WorkflowStatus incomingWorkflowStatus = null;
    // parse json
    for (Iterator<String> it = this.getJsonFeature().keys(); it.hasNext();) {
        String attribute = it.next();
        if (!this.getFID().equals(attribute)) {
            AttributeDescriptor ad = this.getStore().getSchema().getDescriptor(attribute);
            if (ad != null) {
                if (!isAttributeUserEditingDisabled(attribute)) {
                    attributes.add(attribute);
                    if (ad.getType() instanceof GeometryType) {
                        String wkt = this.getJsonFeature().getString(ad.getLocalName());
                        Geometry g = null;
                        if (wkt != null) {
                            g = new WKTReader().read(wkt);
                        }
                        values.add(g);
                    } else {
                        String v = this.getJsonFeature().getString(attribute);
                        values.add(StringUtils.defaultIfBlank(v, null));
                        // remember the incoming workflow status
                        if (attribute.equals(WORKFLOW_FIELDNAME)) {
                            incomingWorkflowStatus = WorkflowStatus.valueOf(v);
                        }
                    }
                } else {
                    log.info(String.format("Attribute \"%s\" not user editable; ignoring", attribute));
                }
            } else {
                log.warn(String.format("Attribute \"%s\" not in feature type; ignoring", attribute));
            }
        }
    }
    log.debug(String.format("Modifying feature source #%d fid=%s, attributes=%s, values=%s",
            this.getLayer().getFeatureType().getId(), fid, attributes.toString(), values.toString()));

    Transaction editTransaction = new DefaultTransaction("ibis_edit");
    this.getStore().setTransaction(editTransaction);
    try {
        if (incomingWorkflowStatus == null) {
            throw new IllegalArgumentException(
                    "Workflow status van edit feature is null, dit wordt niet ondersteund.");
        }
        SimpleFeature original = this.getStore().getFeatures(fidFilter).features().next();
        Object terreinID = original.getAttribute(KAVEL_TERREIN_ID_FIELDNAME);
        WorkflowStatus originalWorkflowStatus = WorkflowStatus
                .valueOf(original.getAttribute(WORKFLOW_FIELDNAME).toString());

        // make a copy of the original feature and set (new) attribute values on the copy
        SimpleFeature editedNewFeature = createCopy(original);
        for (int i = 0; i < attributes.size(); i++) {
            editedNewFeature.setAttribute(attributes.get(i), values.get(i));
        }

        Filter definitief = ff.and(
                ff.equals(ff.property(ID_FIELDNAME), ff.literal(original.getAttribute(ID_FIELDNAME))),
                ff.equal(ff.property(WORKFLOW_FIELDNAME), ff.literal(WorkflowStatus.definitief.name()), false));
        boolean definitiefExists = (this.getStore().getFeatures(definitief).size() > 0);

        Filter bewerkt = ff.and(
                ff.equals(ff.property(ID_FIELDNAME), ff.literal(original.getAttribute(ID_FIELDNAME))),
                ff.equal(ff.property(WORKFLOW_FIELDNAME), ff.literal(WorkflowStatus.bewerkt.name()), false));
        int aantalBewerkt = this.getStore().getFeatures(bewerkt).size();
        boolean bewerktExists = (aantalBewerkt > 0);

        switch (incomingWorkflowStatus) {
        case bewerkt:
            if (originalWorkflowStatus.equals(WorkflowStatus.definitief)) {
                // definitief -> bewerkt
                if (bewerktExists) {
                    // delete existing bewerkt
                    this.getStore().removeFeatures(bewerkt);
                }
                // insert new record with original id and workflowstatus "bewerkt", leave original "definitief"
                this.getStore().addFeatures(DataUtilities.collection(editedNewFeature));
            } else if (originalWorkflowStatus.equals(WorkflowStatus.bewerkt)) {
                // bewerkt -> bewerkt, overwrite, only one 'bewerkt' is allowed
                if (aantalBewerkt > 1) {
                    log.error("Er is meer dan 1 bewerkt kavel/terrein voor " + ID_FIELDNAME + "="
                            + original.getAttribute(ID_FIELDNAME));
                    // more than 1 bewerkt, move them to archief
                    this.getStore().modifyFeatures(WORKFLOW_FIELDNAME, WorkflowStatus.archief, bewerkt);
                }
                this.getStore().modifyFeatures(attributes.toArray(new String[attributes.size()]),
                        values.toArray(), fidFilter);
            } else {
                // other behaviour not documented eg. archief -> bewerkt, afgevoerd -> bewerkt
                //  and not possible to occur in the application as only definitief and bewerkt can be edited
                throw new IllegalArgumentException(
                        String.format("Niet ondersteunde workflow stap van %s naar %s",
                                originalWorkflowStatus.label(), incomingWorkflowStatus.label()));
            }
            break;
        case definitief:
            if (definitiefExists) {
                // check if any "definitief" exists for this id and move that to "archief"
                this.getStore().modifyFeatures(WORKFLOW_FIELDNAME, WorkflowStatus.archief, definitief);
            }
            if (originalWorkflowStatus.equals(WorkflowStatus.definitief)) {
                // if the original was "definitief" insert a new "definitief"
                this.getStore().addFeatures(DataUtilities.collection(editedNewFeature));
            } else if (originalWorkflowStatus.equals(WorkflowStatus.bewerkt)) {
                // if original was "bewerkt" update this to "definitief" with the edits
                this.getStore().modifyFeatures(attributes.toArray(new String[attributes.size()]),
                        values.toArray(), fidFilter);
            } else {
                // other behaviour not documented eg. archief -> definitief, afgevoerd -> definitief
                //  and not possible to occur in the application as only definitief and bewerkt can be edited
                throw new IllegalArgumentException(
                        String.format("Niet ondersteunde workflow stap van %s naar %s",
                                originalWorkflowStatus.label(), incomingWorkflowStatus.label()));
            }
            break;
        case afgevoerd:
            if (definitiefExists) {
                // update any "definitief" for this id to "archief"
                this.getStore().modifyFeatures(WORKFLOW_FIELDNAME, WorkflowStatus.archief, definitief);
            }
            // update original with the new/edited data including "afgevoerd"
            this.getStore().modifyFeatures(attributes.toArray(new String[attributes.size()]), values.toArray(),
                    fidFilter);

            if (terreinID == null) {
                // find any kavels related to this terrein and also set them to "afgevoerd"
                Filter kavelFilter = ff.equals(ff.property(KAVEL_TERREIN_ID_FIELDNAME),
                        ff.literal(original.getAttribute(ID_FIELDNAME)));
                this.updateKavelWorkflowForTerrein(kavelFilter, WorkflowStatus.afgevoerd);
            }
            break;
        case archief: {
            // not described, for now just edit the feature
            this.getStore().modifyFeatures(attributes.toArray(new String[attributes.size()]), values.toArray(),
                    fidFilter);
            break;
        }
        default:
            throw new IllegalArgumentException(
                    "Workflow status van edit feature is null, dit wordt niet ondersteund.");
        }

        editTransaction.commit();
        editTransaction.close();
        // update terrein geometry
        if (terreinID != null) {
            WorkflowUtil.updateTerreinGeometry(Integer.parseInt(terreinID.toString()), this.getLayer(),
                    incomingWorkflowStatus, this.getApplication(), Stripersist.getEntityManager());
        }
    } catch (IllegalArgumentException | IOException | NoSuchElementException e) {
        editTransaction.rollback();
        log.error("Ibis editFeature error", e);
        throw e;
    }
}

From source file:nl.knaw.huygens.timbuctoo.model.cnw.CNWPerson.java

@IndexAnnotation(fieldName = "dynamic_s_shortdescription", canBeEmpty = false, isFaceted = false)
public String getShortDescription() {
    String charString = characteristics.isEmpty() ? "" : ", " + Joiner.on(", ").join(characteristics);
    return MessageFormat.format("{0} ({1}-{2}){3}", //
            StringUtils.defaultIfBlank(getName(), getKoppelnaam()), //
            extractYear(getBirthDate()), //
            extractYear(getDeathDate()), //
            charString);/*from   w  w w  .ja  va  2 s . c  o  m*/
}

From source file:no.kantega.commons.filter.ParamEncodingFilter.java

public void init(FilterConfig filterConfig) throws ServletException {
    String encoding = filterConfig.getInitParameter(POST_PARAM_ENCODING);
    this.encoding = StringUtils.defaultIfBlank(encoding, "utf-8");

    String GETencoding = filterConfig.getInitParameter(GET_PARAM_ENCODING);
    this.GETencoding = StringUtils.defaultIfBlank(GETencoding, "iso-8859-1");
}

From source file:org.biouno.databasesparql.JenaTDBDatabase.java

/**
 * Create a Jena TDB Database. This constructor is exposed to the UI via the {@link DataBoundConstructor}
 * annotation. It overrides the default constructor from the {@link AbstractRemoteDatabase}, as Jena TDB uses
 * only location and other flags, different than other JDBC drivers.
 *
 * @param location TDB database location
 * @param mustExist must-exist flag/*from  ww  w .  ja va 2 s .c  o m*/
 */
@DataBoundConstructor
public JenaTDBDatabase(String location, Boolean mustExist) {
    super("", "", "", Secret.fromString(""), "");
    this.location = StringUtils.defaultIfBlank(location, "");
    this.mustExist = BooleanUtils.toBooleanDefaultIfNull(mustExist, Boolean.FALSE);
}

From source file:org.codice.git.hook.Artifact.java

/**
 * Prompts for the blacklist artifact info.
 *
 * @param in  the reader to read user input from
 * @param out the output stream where to print messages to the user
 * @throws IOException if an error occurs
 *///w w w .j  av  a 2  s  .  c o  m
public void promptInfo(BufferedReader in, PrintStream out) throws IOException {
    this.mvnInfo = null;
    this.mvnName = null;
    LOGGER.log(Level.WARNING, "The {0} file was not found.", name);
    out.printf("%sThe %s file was not found%n", iprefix, name);
    out.printf("%sDo you wish to download it automatically (y/n) [Y]? ", iprefix);
    out.flush();
    final String yn = StringUtils.lowerCase(StringUtils.trim(in.readLine()));

    if (!yn.isEmpty() && (yn.charAt(0) == 'n')) {
        out.printf("%s You can always manually copy the file to: %n", iprefix);
        out.printf("%s    %n", iprefix, file);
        if (!infofile.exists()) { // make sure we no longer cache the info
            infofile.delete();
        }
        return;
    }
    out.println(iprefix);
    out.printf("%sPlease provide the maven artifact's coordinates for the %s file:%n", iprefix, name);
    final String email = handler.getConfigString("user", null, "email");
    String dgroup = null;

    if (StringUtils.isNotEmpty(email)) {
        final int i = email.indexOf('@');

        if (i != -1) {
            final String domain = email.substring(i + 1);
            final int j = domain.indexOf('.');

            if (j != -1) {
                dgroup = domain.substring(j + 1) + '.' + domain.substring(0, j);
            }
        }
    }
    String group;
    final String id;
    final String version;
    final String type;
    final String classifier;

    do {
        if (dgroup == null) {
            do {
                out.printf("%s   group id: ", iprefix);
                out.flush();
                group = StringUtils.trim(in.readLine());
            } while (StringUtils.isEmpty(group));
        } else {
            out.printf("%s   group id [%s]: ", iprefix, dgroup);
            out.flush();
            group = StringUtils.defaultIfBlank(StringUtils.trim(in.readLine()), dgroup);
        }
    } while (StringUtils.isEmpty(group));
    out.printf("%s   artifact id [blacklist-words]: ", iprefix);
    out.flush();
    id = StringUtils.defaultIfBlank(StringUtils.trim(in.readLine()), "blacklist-words");
    out.printf("%s   version [RELEASE]: ", iprefix);
    out.flush();
    version = StringUtils.defaultIfBlank(StringUtils.trim(in.readLine()), "RELEASE");
    out.printf("%s   type [txt]: ", iprefix);
    out.flush();
    type = StringUtils.defaultIfBlank(StringUtils.trim(in.readLine()), "txt");
    out.printf("%s   classifier []: ", iprefix);
    out.flush();
    classifier = StringUtils.trim(in.readLine());
    this.mvnInfo = group + ':' + id + ':' + version + ':' + type;

    if (StringUtils.isNotEmpty(classifier)) {
        this.mvnInfo += ':' + classifier;
    }
    this.mvnName = id + '.' + type;
}

From source file:org.dederem.common.service.ConfigService.java

/**
 * Method to read the configuration./*from ww  w  .  j a  v a2s.  c  o m*/
 *
 * @throws IOException
 *             I/O error.
 */
@PostConstruct
public final void initialize() throws IOException {
    final Properties props = new Properties();
    if (this.configFile.exists()) {
        try (InputStream input = new FileInputStream(this.configFile)) {
            props.load(input);
        }
    }

    this.suites = StringUtils.defaultIfBlank(props.getProperty("suites"), "main, contrib, non-free");
    this.baseRepository = StringUtils.defaultIfBlank(props.getProperty("baseRepository"),
            "http://ftp.de.debian.org/debian/");
}