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

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

Introduction

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

Prototype

public static String defaultIfBlank(String str, String defaultStr) 

Source Link

Document

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

Usage

From source file:org.codice.solr.factory.SolrServerFactory.java

private static void createSolrCore(String url, String coreName, String configFileName, HttpClient client) {
    HttpSolrServer solrServer;/*from   w  w w.j  ava  2 s. c  om*/
    if (client != null) {
        solrServer = new HttpSolrServer(url, client);
    } else {
        solrServer = new HttpSolrServer(url);
    }

    if (!solrCoreExists(solrServer, coreName)) {
        LOGGER.info("Creating Solr core {}", coreName);

        String instanceDir = System.getProperty("karaf.home") + "/data/solr/" + coreName;
        String configFile = StringUtils.defaultIfBlank(configFileName, DEFAULT_SOLRCONFIG_XML);

        try {
            CoreAdminRequest.createCore(coreName, instanceDir, solrServer, configFile, DEFAULT_SCHEMA_XML);
        } catch (SolrServerException e) {
            LOGGER.error("SolrServerException creating " + coreName + " core", e);
        } catch (IOException e) {
            LOGGER.error("IOException creating " + coreName + " core", e);
        }
    } else {
        LOGGER.info("Solr core {} already exists - just reload it", coreName);
        try {
            CoreAdminRequest.reloadCore(coreName, solrServer);
        } catch (SolrServerException e) {
            LOGGER.error("SolrServerException reloading " + coreName + " core", e);
        } catch (IOException e) {
            LOGGER.error("IOException reloading " + coreName + " core", e);
        }
    }
}

From source file:org.csanchez.jenkins.plugins.kubernetes.KubernetesLauncher.java

@Override
public void launch(SlaveComputer computer, TaskListener listener) {
    PrintStream logger = listener.getLogger();

    if (!(computer instanceof KubernetesComputer)) {
        throw new IllegalArgumentException("This Launcher can be used only with KubernetesComputer");
    }//ww  w . ja  va  2 s .  com
    KubernetesComputer kubernetesComputer = (KubernetesComputer) computer;
    computer.setAcceptingTasks(false);
    KubernetesSlave slave = kubernetesComputer.getNode();
    if (slave == null) {
        throw new IllegalStateException("Node has been removed, cannot launch " + computer.getName());
    }
    if (launched) {
        LOGGER.log(INFO, "Agent has already been launched, activating: {}", slave.getNodeName());
        computer.setAcceptingTasks(true);
        return;
    }

    KubernetesCloud cloud = slave.getKubernetesCloud();
    final PodTemplate unwrappedTemplate = slave.getTemplate();
    try {
        KubernetesClient client = cloud.connect();
        Pod pod = getPodTemplate(client, slave, unwrappedTemplate);

        String podId = pod.getMetadata().getName();
        String namespace = StringUtils.defaultIfBlank(slave.getNamespace(), client.getNamespace());

        LOGGER.log(Level.FINE, "Creating Pod: {0} in namespace {1}", new Object[] { podId, namespace });
        pod = client.pods().inNamespace(namespace).create(pod);
        LOGGER.log(INFO, "Created Pod: {0} in namespace {1}", new Object[] { podId, namespace });
        logger.printf("Created Pod: %s in namespace %s%n", podId, namespace);

        // We need the pod to be running and connected before returning
        // otherwise this method keeps being called multiple times
        List<String> validStates = ImmutableList.of("Running");

        int i = 0;
        int j = 100; // wait 600 seconds

        List<ContainerStatus> containerStatuses = null;

        // wait for Pod to be running
        for (; i < j; i++) {
            LOGGER.log(INFO, "Waiting for Pod to be scheduled ({1}/{2}): {0}", new Object[] { podId, i, j });
            logger.printf("Waiting for Pod to be scheduled (%2$s/%3$s): %1$s%n", podId, i, j);

            Thread.sleep(6000);
            pod = client.pods().inNamespace(namespace).withName(podId).get();
            if (pod == null) {
                throw new IllegalStateException("Pod no longer exists: " + podId);
            }

            containerStatuses = pod.getStatus().getContainerStatuses();
            List<ContainerStatus> terminatedContainers = new ArrayList<>();
            Boolean allContainersAreReady = true;
            for (ContainerStatus info : containerStatuses) {
                if (info != null) {
                    if (info.getState().getWaiting() != null) {
                        // Pod is waiting for some reason
                        LOGGER.log(INFO, "Container is waiting {0} [{2}]: {1}",
                                new Object[] { podId, info.getState().getWaiting(), info.getName() });
                        logger.printf("Container is waiting %1$s [%3$s]: %2$s%n", podId,
                                info.getState().getWaiting(), info.getName());
                        // break;
                    }
                    if (info.getState().getTerminated() != null) {
                        terminatedContainers.add(info);
                    } else if (!info.getReady()) {
                        allContainersAreReady = false;
                    }
                }
            }

            if (!terminatedContainers.isEmpty()) {
                Map<String, Integer> errors = terminatedContainers.stream().collect(Collectors.toMap(
                        ContainerStatus::getName, (info) -> info.getState().getTerminated().getExitCode()));

                // Print the last lines of failed containers
                logLastLines(terminatedContainers, podId, namespace, slave, errors, client);
                throw new IllegalStateException("Containers are terminated with exit codes: " + errors);
            }

            if (!allContainersAreReady) {
                continue;
            }

            if (validStates.contains(pod.getStatus().getPhase())) {
                break;
            }
        }
        String status = pod.getStatus().getPhase();
        if (!validStates.contains(status)) {
            throw new IllegalStateException(
                    "Container is not running after " + j + " attempts, status: " + status);
        }

        j = unwrappedTemplate.getSlaveConnectTimeout();

        // now wait for agent to be online
        for (; i < j; i++) {
            if (slave.getComputer() == null) {
                throw new IllegalStateException("Node was deleted, computer is null");
            }
            if (slave.getComputer().isOnline()) {
                break;
            }
            LOGGER.log(INFO, "Waiting for agent to connect ({1}/{2}): {0}", new Object[] { podId, i, j });
            logger.printf("Waiting for agent to connect (%2$s/%3$s): %1$s%n", podId, i, j);
            Thread.sleep(1000);
        }
        if (!slave.getComputer().isOnline()) {
            if (containerStatuses != null) {
                logLastLines(containerStatuses, podId, namespace, slave, null, client);
            }
            throw new IllegalStateException(
                    "Agent is not connected after " + j + " attempts, status: " + status);
        }
        computer.setAcceptingTasks(true);
    } catch (Throwable ex) {
        LOGGER.log(Level.WARNING,
                String.format("Error in provisioning; agent=%s, template=%s", slave, unwrappedTemplate), ex);
        LOGGER.log(Level.FINER, "Removing Jenkins node: {0}", slave.getNodeName());
        try {
            slave.terminate();
        } catch (IOException | InterruptedException e) {
            LOGGER.log(Level.WARNING, "Unable to remove Jenkins node", e);
        }
        throw Throwables.propagate(ex);
    }
    launched = true;
    try {
        // We need to persist the "launched" setting...
        slave.save();
    } catch (IOException e) {
        LOGGER.log(Level.WARNING, "Could not save() agent: " + e.getMessage(), e);
    }
}

From source file:org.eclipse.jubula.client.ui.rcp.dialogs.VersionComposite.java

/**
 * @param area The composite. creates the text field to edit the TestSuite name.
 * @param version the inital version for the fields
 *///from w w  w.ja  v a  2  s. com
private void createVersionFields(Composite area, ProjectVersion version) {
    new Label(area, SWT.NONE).setText(Messages.CreateNewProjectVersionActionVersionNumbers);
    m_majorVersionField = new CheckedIntText(area, SWT.SINGLE | SWT.BORDER, true, 0, Integer.MAX_VALUE);
    GridData gridData = newGridData();
    LayoutUtil.addToolTipAndMaxWidth(gridData, m_majorVersionField);
    gridData.widthHint = Dialog.convertWidthInCharsToPixels(LayoutUtil.getFontMetrics(m_majorVersionField), 10);
    m_majorVersionField.setLayoutData(gridData);
    m_majorVersionField.setText(version.getMajorNumber() != null ? String.valueOf(version.getMajorNumber())
            : StringConstants.EMPTY);
    LayoutUtil.setMaxChar(m_majorVersionField, m_length);
    m_majorVersionField.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            modifyVersionFieldAction();
        }
    });
    m_majorVersionField.setData(SwtToolkitConstants.WIDGET_NAME, "VersionComposite.MajorVersionField"); //$NON-NLS-1$

    m_minorVersionField = new CheckedIntText(area, SWT.SINGLE | SWT.BORDER, true, 0, Integer.MAX_VALUE);
    gridData = newGridData();
    LayoutUtil.addToolTipAndMaxWidth(gridData, m_minorVersionField);
    gridData.widthHint = Dialog.convertWidthInCharsToPixels(LayoutUtil.getFontMetrics(m_minorVersionField), 10);
    m_minorVersionField.setLayoutData(gridData);
    m_minorVersionField.setText(version.getMinorNumber() != null ? String.valueOf(version.getMinorNumber())
            : StringConstants.EMPTY);
    LayoutUtil.setMaxChar(m_minorVersionField, m_length);
    m_minorVersionField.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            modifyVersionFieldAction();
        }
    });
    m_minorVersionField.setData(SwtToolkitConstants.WIDGET_NAME, "VersionComposite.MinorVersionField"); //$NON-NLS-1$
    m_microVersionField = new CheckedIntText(area, SWT.SINGLE | SWT.BORDER, true, 0, Integer.MAX_VALUE);
    gridData = newGridData();
    LayoutUtil.addToolTipAndMaxWidth(gridData, m_microVersionField);
    gridData.widthHint = Dialog.convertWidthInCharsToPixels(LayoutUtil.getFontMetrics(m_microVersionField), 10);
    m_microVersionField.setLayoutData(gridData);
    m_microVersionField.setText(version.getMicroNumber() != null ? String.valueOf(version.getMicroNumber())
            : StringConstants.EMPTY);
    LayoutUtil.setMaxChar(m_microVersionField, m_length);
    m_microVersionField.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            modifyVersionFieldAction();
        }
    });
    m_microVersionField.setData(SwtToolkitConstants.WIDGET_NAME, "VersionComposite.MicroVersionField"); //$NON-NLS-1$
    new Label(area, SWT.NONE).setText(Messages.CreateNewProjectVersionActionQualifierLabel);
    m_versionQualifierField = new Text(area, SWT.SINGLE | SWT.BORDER);
    gridData = newGridData();
    LayoutUtil.addToolTipAndMaxWidth(gridData, m_versionQualifierField);
    gridData.widthHint = 0;
    gridData.horizontalSpan = 3;
    gridData.horizontalAlignment = GridData.FILL;
    m_versionQualifierField.setLayoutData(gridData);
    m_versionQualifierField
            .setText(StringUtils.defaultIfBlank(version.getVersionQualifier(), StringConstants.EMPTY));
    LayoutUtil.setMaxChar(m_versionQualifierField, m_length);
    m_versionQualifierField.addModifyListener(new ModifyListener() {
        public void modifyText(ModifyEvent e) {
            modifyVersionFieldAction();
        }
    });
    m_versionQualifierField.setData(SwtToolkitConstants.WIDGET_NAME, "VersionComposite.VersionQualifierField"); //$NON-NLS-1$
}

From source file:org.fao.geonet.services.harvesting.Get.java

public Element exec(Element params, ServiceContext context) throws Exception {
    //--- if 'id' is null all entries are returned

    @SuppressWarnings("unchecked")
    List<Element> idEls = params.getChildren("id");
    boolean onlyInfo = org.fao.geonet.Util.getParam(params, "onlyInfo", false);
    String sortField = org.fao.geonet.Util.getParam(params, "sortField", "site[1]/name[1]");

    GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME);
    final SettingManager settingManager = gc.getApplicationContext().getBean(SettingManager.class);
    String[] disabledTypes = StringUtils.split(StringUtils
            .defaultIfBlank(settingManager.getValue(Settings.SYSTEM_HARVESTER_DISABLED_HARVESTER_TYPES), "")
            .toLowerCase().replace(',', ' '), " ");

    List<String> ids;
    if (idEls.isEmpty()) {
        ids = Collections.singletonList(null);
    } else {/*  w ww  . java  2s .c o m*/
        ids = idEls.stream().map(Element::getTextTrim).collect(Collectors.toList());
    }
    final HarvestManager harvestManager = gc.getBean(HarvestManager.class);
    Element result = new Element("nodes");
    for (String id : ids) {
        Element node = harvestManager.get(id, context, sortField);

        if (node != null) {
            if (idEls.isEmpty() || id.equals("-1")) {
                List<Element> childNodes = node.getChildren();
                for (Element childNode : childNodes) {
                    String harvesterType = childNode.getAttributeValue("type");
                    if (Arrays.stream(disabledTypes)
                            .noneMatch(disabledType -> disabledType.equalsIgnoreCase(harvesterType))) {
                        result.addContent((Content) childNode.clone());
                    }
                }
            } else {
                String harvesterType = node.getAttributeValue("type");
                if (Arrays.stream(disabledTypes)
                        .noneMatch(disabledType -> disabledType.equalsIgnoreCase(harvesterType))) {
                    result.addContent(node.detach());
                }
            }
        } else {
            throw new ObjectNotFoundEx("No Harvester found with id: " + id);
        }
    }

    if (onlyInfo) {
        removeAllDataExceptInfo(result);
    }

    return result;
}

From source file:org.hako.dao.mapper.AnnotationMapper.java

public EntityMeta setUp(Class<?> clazz) {
    if (!clazz.isAnnotationPresent(Entity.class)) {
        throw new IllegalArgumentException("class must with Entity annotation");
    }//from w  w  w .j  a v  a 2  s.c o  m
    Entity entityAnno = clazz.getAnnotation(Entity.class);
    String tableName = StringUtils.defaultIfBlank(entityAnno.tableName(), clazz.getSimpleName());
    String alias = StringUtils.defaultIfBlank(entityAnno.tableAlias(), tableName);
    EntityName entityName = new EntityName(tableName, alias);
    // setup fields
    List<FieldMeta> fields = new ArrayList<FieldMeta>();
    for (java.lang.reflect.Field f : clazz.getFields()) {
        if (f.isAnnotationPresent(Field.class)) {
            String propertyName = f.getName();
            Field fieldAnno = f.getAnnotation(Field.class);
            String columnName = StringUtils.defaultIfBlank(fieldAnno.columnName(),
                    toDashSeparated(propertyName));
            fields.add(new FieldMeta(columnName, propertyName, f.isAnnotationPresent(Id.class)));
        }
    }
    return new EntityMeta(entityName, fields);
}

From source file:org.intermine.webservice.server.template.TemplateUploadService.java

@Override
protected void execute() throws Exception {

    String templatesXML = "";
    if ("application/x-www-form-urlencoded".equals(request.getContentType())
            || "GET".equalsIgnoreCase(request.getMethod())) {
        templatesXML = getRequiredParameter(TEMPLATES_PARAMETER);
    } else {// w  w  w  .  j a v a2  s  .  c om
        templatesXML = IOUtils.toString(request.getInputStream());
    }
    Profile profile = getPermission().getProfile();

    int version = getIntParameter(VERSION_PARAMETER, TemplateQuery.USERPROFILE_VERSION);
    Reader r = new StringReader(templatesXML);

    Map<String, TemplateQuery> templates;
    try {
        templates = TemplateQueryBinding.unmarshalTemplates(r, version);
    } catch (Exception e) {
        throw new BadRequestException("Could not parse templates: " + e.getMessage(), e);
    }
    for (TemplateQuery t : templates.values()) {
        if (!t.isValid()) {
            String message = String.format("Query %s contains errors: %s",
                    StringUtils.defaultIfBlank(t.getName(), "NO-NAME"), formatMessage(t.verifyQuery()));
            throw new BadRequestException(message);
        }
    }

    for (Entry<String, TemplateQuery> pair : templates.entrySet()) {
        String name = pair.getKey();
        try {
            profile.saveTemplate(name, new ApiTemplate(pair.getValue()));
        } catch (BadTemplateException bte) {
            throw new BadRequestException("The template has an invalid name.");
        } catch (RuntimeException e) {
            throw new ServiceException("Failed to save template: " + name, e);
        }
    }
}

From source file:org.itracker.model.util.IssueUtilities.java

public static String getRelationName(IssueRelation.Type value, Locale locale) {
    return StringUtils.defaultIfBlank(
            ITrackerResources.getString(ITrackerResources.KEY_BASE_ISSUE_RELATION + value.getCode(), locale),
            value.name());//from   w  w  w. j  a  v a2  s. c o  m
}

From source file:org.itracker.model.util.IssueUtilities.java

public static String getStatusName(String value, Locale locale) {
    return StringUtils.defaultIfBlank(
            ITrackerResources.getString(ITrackerResources.KEY_BASE_STATUS + value, locale), value);
}

From source file:org.itracker.model.util.IssueUtilities.java

public static String getSeverityName(Integer value) {
    return StringUtils.defaultIfBlank(getSeverityName(value, ITrackerResources.getLocale()),
            String.valueOf(value));
}

From source file:org.itracker.model.util.IssueUtilities.java

public static String getSeverityName(Integer value, Locale locale) {
    return StringUtils.defaultIfBlank(getSeverityName(Integer.toString(value), locale), String.valueOf(value));
}