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

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

Introduction

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

Prototype

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

Source Link

Document

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

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

Usage

From source file:info.magnolia.ui.framework.command.ImportZipCommand.java

protected void handleFileEntry(ZipFile zip, ZipArchiveEntry entry) throws IOException, RepositoryException {
    String fileName = entry.getName();
    if (StringUtils.contains(fileName, "/")) {
        fileName = StringUtils.substringAfterLast(fileName, "/");
    }//  ww  w . j  av  a2 s .  c om

    String extension = StringUtils.substringAfterLast(fileName, ".");
    InputStream stream = zip.getInputStream(entry);
    FileOutputStream os = null;
    try {
        UploadReceiver receiver = createReceiver();

        String folderPath = extractEntryPath(entry);
        if (folderPath.startsWith("/")) {
            folderPath = folderPath.substring(1);
        }
        Node folder = getJCRNode(context);
        if (StringUtils.isNotBlank(folderPath)) {
            if (folder.hasNode(folderPath)) {
                folder = folder.getNode(folderPath);
            } else {
                folder = NodeUtil.createPath(folder, folderPath, NodeTypes.Folder.NAME, true);
            }
        }
        receiver.setFieldType(UploadField.FieldType.BYTE_ARRAY);
        receiver.receiveUpload(fileName,
                StringUtils.defaultIfEmpty(MIMEMapping.getMIMEType(extension), DEFAULT_MIME_TYPE));
        receiver.setValue(IOUtils.toByteArray(stream));

        doHandleEntryFromReceiver(folder, receiver);
    } catch (IOException e) {
        throw e;
    } finally {
        IOUtils.closeQuietly(stream);
        IOUtils.closeQuietly(os);
    }
}

From source file:com.base2.kagura.core.report.parameterTypes.ParamConfig.java

/**
 * The parameter ID. Used by FreeMarker to reference the parameter. If ID hasn't been specified it bases it on the
 * name by removing all non-"word" characters (it only allows a-zA-Z.) So:
 * Tom's Param-//  w w  w.jav  a  2s. co  m
 * Becomes
 * TomsParam
 * @return
 */
public String getId() {
    Pattern replace = Pattern.compile("\\W+");
    return StringUtils.defaultIfEmpty(id, replace.matcher(getName()).replaceAll(""));
}

From source file:info.magnolia.ui.admincentral.shellapp.favorites.FavoritesPresenter.java

public JcrNewNodeAdapter determinePreviousLocation() {
    JcrNewNodeAdapter favoriteLocation;/*from  w  w  w  . ja  va  2 s.c om*/

    // at this point the current location in the browser hasn't yet changed to favorite shellapp,
    // so it is what we need to pre-populate the form for creating a new favorite
    final URI previousLocation = Page.getCurrent().getLocation();
    final String previousLocationFragment = previousLocation.getFragment();

    // skip bookmark resolution if for some reason fragment is empty
    if (previousLocationFragment == null) {
        return createNewFavoriteSuggestion("", "", "");
    }

    final String appName = DefaultLocation.extractAppName(previousLocationFragment);
    final String appType = DefaultLocation.extractAppType(previousLocationFragment);
    // TODO MGNLUI-1190 should this be added to DefaultLocation as a convenience static method?
    final String path = StringUtils.substringBetween(previousLocationFragment, ";", ":");

    // skip bookmark resolution shell apps
    if (Location.LOCATION_TYPE_SHELL_APP.equals(appType)) {
        favoriteLocation = createNewFavoriteSuggestion("", "", "");
    } else {
        final AppDescriptor appDescriptor;

        try {
            DefinitionProvider<AppDescriptor> definitionProvider = appDescriptorRegistry.getProvider(appName);
            appDescriptor = i18nizer.decorate(definitionProvider.get());
        } catch (Registry.NoSuchDefinitionException | IllegalStateException e) {
            throw new RuntimeException(e);
        }

        final String appIcon = StringUtils.defaultIfEmpty(appDescriptor.getIcon(), "icon-app");
        final String title = appDescriptor.getLabel() + " " + (path == null ? "/" : path);
        final String urlFragment = getUrlFragmentFromURI(previousLocation);
        favoriteLocation = createNewFavoriteSuggestion(urlFragment, title, appIcon);
    }
    return favoriteLocation;
}

From source file:com.hurence.logisland.engine.vanilla.stream.amqp.AmqpClientPipelineStream.java

private CompletableFuture<ProtonConnection> setupConnection() {
    CompletableFuture<ProtonConnection> completableFuture = new CompletableFuture<>();
    String hostname = streamContext.getPropertyValue(StreamOptions.CONNECTION_HOST).asString();
    int port = streamContext.getPropertyValue(StreamOptions.CONNECTION_PORT).asInteger();
    int credits = streamContext.getPropertyValue(StreamOptions.LINK_CREDITS).asInteger();

    String user = streamContext.getPropertyValue(StreamOptions.CONNECTION_AUTH_USERNAME).asString();
    String password = streamContext.getPropertyValue(StreamOptions.CONNECTION_AUTH_PASSWORD).asString();
    if (user != null && password != null) {
        options.addEnabledSaslMechanism("PLAIN");
    } else if (streamContext.getPropertyValue(StreamOptions.CONNECTION_AUTH_TLS_CERT).isSet()) {
        String tlsCert = streamContext.getPropertyValue(StreamOptions.CONNECTION_AUTH_TLS_CERT).asString();
        String tlsKey = streamContext.getPropertyValue(StreamOptions.CONNECTION_AUTH_TLS_KEY).asString();
        String caCert = streamContext.getPropertyValue(StreamOptions.CONNECTION_AUTH_CA_CERT).asString();
        options.addEnabledSaslMechanism("EXTERNAL").setHostnameVerificationAlgorithm("")
                .setPemKeyCertOptions(new PemKeyCertOptions().addCertPath(new File(tlsCert).getAbsolutePath())
                        .addKeyPath(new File(tlsKey).getAbsolutePath()));
        if (caCert != null) {
            options.setPemTrustOptions(new PemTrustOptions().addCertPath(new File(caCert).getAbsolutePath()));
        }// www.j a v  a  2 s.  c  om

    }
    protonClient.connect(options, hostname, port, user, password, event -> {
        if (event.failed()) {
            handleConnectionFailure(false);
            completableFuture.completeExceptionally(event.cause());
            return;
        }
        connectionControl.connected();
        completableFuture.complete(event.result());
        protonConnection = event.result();
        String containerId = streamContext.getPropertyValue(StreamOptions.CONTAINER_ID).asString();
        if (containerId != null) {
            protonConnection.setContainer(containerId);
        }
        protonConnection.closeHandler(x -> {
            handleConnectionFailure(true);
        }).disconnectHandler(x -> {
            handleConnectionFailure(false);
        }).openHandler(onOpen -> {

            //setup the output path
            sender = protonConnection
                    .createSender(streamContext.getPropertyValue(StreamOptions.WRITE_TOPIC).asString());
            sender.setAutoDrained(true);
            sender.setAutoSettle(true);
            sender.open();

            //setup the input path
            receiver = protonConnection
                    .createReceiver(streamContext.getPropertyValue(StreamOptions.READ_TOPIC).asString());
            receiver.setPrefetch(credits);
            receiver.handler((delivery, message) -> {
                try {
                    Record record;
                    if (deserializer == null) {
                        record = RecordUtils.getKeyValueRecord(
                                StringUtils.defaultIfEmpty(message.getSubject(), ""),
                                new String(extractBodyContent(message.getBody())));
                    } else {
                        record = deserializer
                                .deserialize(new ByteArrayInputStream(extractBodyContent(message.getBody())));
                        if (!record.hasField(FieldDictionary.RECORD_KEY)) {
                            record.setField(FieldDictionary.RECORD_KEY, FieldType.STRING, message.getSubject());
                        }
                    }

                    Collection<Record> r = Collections.singleton(record);
                    for (ProcessContext processContext : streamContext.getProcessContexts()) {
                        r = processContext.getProcessor().process(processContext, r);
                    }
                    List<Message> toAdd = new ArrayList<>();
                    for (Record out : r) {
                        ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
                        serializer.serialize(byteOutputStream, out);
                        Message mo = ProtonHelper.message();
                        if (out.hasField(FieldDictionary.RECORD_KEY)) {
                            mo.setSubject(out.getField(FieldDictionary.RECORD_KEY).asString());
                        }
                        if (StringUtils.isNotBlank(contentType)) {
                            mo.setContentType(contentType);
                        }
                        mo.setMessageId(out.getId());
                        mo.setBody(new Data(Binary.create(ByteBuffer.wrap(byteOutputStream.toByteArray()))));
                        toAdd.add(mo);
                    }
                    toAdd.forEach(sender::send);
                    delivery.disposition(Accepted.getInstance(), true);
                } catch (Exception e) {
                    Rejected rejected = new Rejected();
                    delivery.disposition(rejected, true);
                    getLogger().warn("Unable to process message : " + e.getMessage());
                }
            }).open();

        }).open();

    });
    return completableFuture;
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlArea.java

/**
 * Indicates if this area contains the specified point.
 * @param x the x coordinate of the point
 * @param y the y coordinate of the point
 * @return {@code true} if the point is contained in this area
 *//*from w ww.  j  ava 2s  . c  o m*/
boolean containsPoint(final int x, final int y) {
    final String shape = StringUtils.defaultIfEmpty(getShapeAttribute(), "rect").toLowerCase(Locale.ROOT);

    if ("default".equals(shape) && getCoordsAttribute() != null) {
        return true;
    }

    if ("rect".equals(shape) && getCoordsAttribute() != null) {
        final Rectangle2D rectangle = parseRect();
        return rectangle.contains(x, y);
    }

    if ("circle".equals(shape) && getCoordsAttribute() != null) {
        final Ellipse2D ellipse = parseCircle();
        return ellipse.contains(x, y);
    }

    if ("poly".equals(shape) && getCoordsAttribute() != null) {
        final GeneralPath path = parsePoly();
        return path.contains(x, y);
    }

    return false;
}

From source file:info.magnolia.ui.admincentral.shellapp.favorites.FavoritesManagerImpl.java

@Override
public JcrNewNodeAdapter createFavoriteSuggestion(String location, String title, String icon) {
    Node bookmarkRoot;//from  ww  w  . ja  v  a 2s. c  o  m
    try {
        bookmarkRoot = favoriteStore.getBookmarkRoot();
    } catch (RepositoryException e) {
        throw new RuntimeRepositoryException(e);
    }

    JcrNewNodeAdapter newFavorite = new JcrNewNodeAdapter(bookmarkRoot, AdmincentralNodeTypes.Favorite.NAME);
    newFavorite.addItemProperty(AdmincentralNodeTypes.Favorite.TITLE,
            DefaultPropertyUtil.newDefaultProperty("", title));
    newFavorite.addItemProperty(AdmincentralNodeTypes.Favorite.URL,
            DefaultPropertyUtil.newDefaultProperty("", location));
    newFavorite.addItemProperty(AdmincentralNodeTypes.Favorite.GROUP,
            DefaultPropertyUtil.newDefaultProperty("", ""));
    newFavorite.addItemProperty(AdmincentralNodeTypes.Favorite.ICON,
            DefaultPropertyUtil.newDefaultProperty("", StringUtils.defaultIfEmpty(icon, "icon-app")));
    return newFavorite;
}

From source file:com.gst.infrastructure.campaigns.sms.domain.SmsCampaign.java

public Map<String, Object> update(JsonCommand command) {

    final Map<String, Object> actualChanges = new LinkedHashMap<>(5);

    if (command.isChangeInStringParameterNamed(SmsCampaignValidator.campaignName, this.campaignName)) {
        final String newValue = command.stringValueOfParameterNamed(SmsCampaignValidator.campaignName);
        actualChanges.put(SmsCampaignValidator.campaignName, newValue);
        this.campaignName = StringUtils.defaultIfEmpty(newValue, null);
    }/*from  w w w.  j  a  v a 2 s.co m*/
    if (command.isChangeInStringParameterNamed(SmsCampaignValidator.message, this.message)) {
        final String newValue = command.stringValueOfParameterNamed(SmsCampaignValidator.message);
        actualChanges.put(SmsCampaignValidator.message, newValue);
        this.message = StringUtils.defaultIfEmpty(newValue, null);
    }
    if (command.isChangeInStringParameterNamed(SmsCampaignValidator.paramValue, this.paramValue)) {
        final String newValue = command.jsonFragment(SmsCampaignValidator.paramValue);
        actualChanges.put(SmsCampaignValidator.paramValue, newValue);
        this.paramValue = StringUtils.defaultIfEmpty(newValue, null);
    }
    if (command.isChangeInIntegerParameterNamed(SmsCampaignValidator.campaignType, this.campaignType)) {
        final Integer newValue = command.integerValueOfParameterNamed(SmsCampaignValidator.campaignType);
        actualChanges.put(SmsCampaignValidator.campaignType, CampaignType.fromInt(newValue));
        this.campaignType = CampaignType.fromInt(newValue).getValue();
    }

    if (command.isChangeInIntegerParameterNamed(SmsCampaignValidator.triggerType, this.triggerType)) {
        final Integer newValue = command.integerValueOfParameterNamed(SmsCampaignValidator.triggerType);
        actualChanges.put(SmsCampaignValidator.triggerType, SmsCampaignTriggerType.fromInt(newValue));
        this.triggerType = SmsCampaignTriggerType.fromInt(newValue).getValue();
    }

    if (command.isChangeInLongParameterNamed(SmsCampaignValidator.runReportId,
            (this.businessRuleId != null) ? this.businessRuleId.getId() : null)) {
        final String newValue = command.stringValueOfParameterNamed(SmsCampaignValidator.runReportId);
        actualChanges.put(SmsCampaignValidator.runReportId, newValue);
    }
    if (command.isChangeInStringParameterNamed(SmsCampaignValidator.recurrenceParamName, this.recurrence)) {
        final String newValue = command.stringValueOfParameterNamed(SmsCampaignValidator.recurrenceParamName);
        actualChanges.put(SmsCampaignValidator.recurrenceParamName, newValue);
        this.recurrence = StringUtils.defaultIfEmpty(newValue, null);
    }
    if (command.isChangeInLongParameterNamed(SmsCampaignValidator.providerId, this.providerId)) {
        final Long newValue = command.longValueOfParameterNamed(SmsCampaignValidator.providerId);
        actualChanges.put(SmsCampaignValidator.providerId, newValue);
    }

    if (SmsCampaignTriggerType.fromInt(this.triggerType).isSchedule()) {
        final String dateFormatAsInput = command.dateFormat();
        final String dateTimeFormatAsInput = command
                .stringValueOfParameterNamed(SmsCampaignValidator.dateTimeFormat);
        final String localeAsInput = command.locale();
        final Locale locale = command.extractLocale();
        final DateTimeFormatter fmt = DateTimeFormat.forPattern(dateTimeFormatAsInput).withLocale(locale);
        final String valueAsInput = command
                .stringValueOfParameterNamed(SmsCampaignValidator.recurrenceStartDate);
        actualChanges.put(SmsCampaignValidator.recurrenceStartDate, valueAsInput);
        actualChanges.put(SmsCampaignValidator.dateFormatParamName, dateFormatAsInput);
        actualChanges.put(SmsCampaignValidator.dateTimeFormat, dateTimeFormatAsInput);
        actualChanges.put(SmsCampaignValidator.localeParamName, localeAsInput);

        final LocalDateTime newValue = LocalDateTime.parse(valueAsInput, fmt);

        this.recurrenceStartDate = newValue.toDate();
    }

    return actualChanges;
}

From source file:edu.toronto.cs.phenotips.tools.PropertyDisplayer.java

private FormElement generateField(String id, String title, boolean expandable, boolean yesSelected,
        boolean noSelected) {
    String hint = getLabelFromOntology(id);
    if (id.equals(hint) && title != null) {
        hint = title;//from w ww .  j av  a2  s .c  o  m
    }
    String metadata = "";
    Map<String, String> metadataValues = this.metadata.get(id);
    if (metadataValues != null) {
        metadata = metadataValues
                .get(noSelected ? this.data.getNegativePropertyName() : this.data.getPositivePropertyName());
    }
    return new FormField(id, StringUtils.defaultIfEmpty(title, hint), hint, StringUtils.defaultString(metadata),
            expandable, yesSelected, noSelected);
}

From source file:com.base2.kagura.core.report.connectors.FreemarkerSQLDataReportConnector.java

/**
 * Returns a preparedStatement result into a List of Maps. Not the most efficient way of storing the values, however
 * the results should be limited at this stage.
 * @param rows The result set.//from  w  w w . j  a v  a2 s .c o m
 * @return Mapped results.
 * @throws RuntimeException upon any error, adds values to "errors"
 */
public List<Map<String, Object>> resultSetToMap(ResultSet rows) {
    try {
        List<Map<String, Object>> beans = new ArrayList<Map<String, Object>>();
        int columnCount = rows.getMetaData().getColumnCount();
        while (rows.next()) {
            LinkedHashMap<String, Object> bean = new LinkedHashMap<String, Object>();
            beans.add(bean);
            for (int i = 0; i < columnCount; i++) {
                Object object = rows.getObject(i + 1);
                String columnLabel = rows.getMetaData().getColumnLabel(i + 1);
                String columnName = rows.getMetaData().getColumnName(i + 1);
                bean.put(StringUtils.defaultIfEmpty(columnLabel, columnName),
                        object != null ? object.toString() : "");
            }
        }
        return beans;
    } catch (Exception ex) {
        errors.add(ex.getMessage());
        throw new RuntimeException(ex);
    }
}

From source file:com.webbfontaine.valuewebb.model.template.Template.java

public String generateSpec() {
    if (getSpec() == null) {
        logger.warn(/*from w  ww  .java2s . co m*/
                "Attempt to generate specification code for Template which does not have specification defined!");
        return null;
    }

    StringBuffer specCode = new StringBuffer(64);
    try {
        Method[] fws = Template.class.getMethods();
        for (Method fw : fws) {
            if (!fw.getName().startsWith("getFw")) {
                continue;
            }
            Integer weight = (Integer) fw.invoke(this);
            if (weight != null && weight != 0) {
                String numberOfField = fw.getName().split("getFw")[1];
                String fValueCode = (String) Template.class.getMethod("getF" + numberOfField).invoke(this);
                specCode.append(StringUtils.defaultIfEmpty(fValueCode, "-"));
            }
        }
    } catch (Exception e) {
        logger.error("Error during Specification code generation", e);
    }

    return specCode.toString();
}