Example usage for com.google.common.base Strings emptyToNull

List of usage examples for com.google.common.base Strings emptyToNull

Introduction

In this page you can find the example usage for com.google.common.base Strings emptyToNull.

Prototype

@Nullable
public static String emptyToNull(@Nullable String string) 

Source Link

Document

Returns the given string if it is nonempty; null otherwise.

Usage

From source file:org.envirocar.server.mongo.entity.MongoFueling.java

@Override
public void setComment(@Nullable String comment) {
    this.comment = Strings.emptyToNull(comment);
}

From source file:org.dcache.alarms.server.LogEntryServerWrapper.java

public void setConfigFile(String configFile) {
    this.configFile = Strings.emptyToNull(configFile);
}

From source file:org.fenixedu.academic.domain.person.HumanName.java

private static HumanName decompose(String fullname) {
    String[] parts = fullname.split("\\s+");
    List<String> prefixes = new ArrayList<>();
    List<String> given = new ArrayList<>();
    List<String> family = new ArrayList<>();
    List<String> sufixes = new ArrayList<>();
    Joiner joiner = Joiner.on(' ');
    int i;//from   www .  ja v  a  2 s .  c  o  m
    for (i = 0; i < parts.length
            && knwonPrefixes.contains(parts[i].toLowerCase().replace('.', ' ').trim()); i++) {
        prefixes.add(parts[i]);
    }
    int j;
    for (j = parts.length - 1; j > 0
            && knwonSuffixes.contains(parts[j].toLowerCase().replace('.', ' ').trim()); j--) {
        prefixes.add(parts[j]);
    }
    Collections.reverse(sufixes);
    int givenCount = (j - i + 1 >= 4) ? 2 : 1;
    int k;
    for (k = i; k < parts.length && givenCount > 0; k++) {
        given.add(parts[k]);
        if (!prepositions.contains(parts[k])) {
            givenCount--;
        }
    }
    for (; k <= j; k++) {
        family.add(parts[k]);
    }
    return new HumanName(Strings.emptyToNull(joiner.join(prefixes)), joiner.join(given), joiner.join(family),
            Strings.emptyToNull(joiner.join(sufixes)));
}

From source file:com.google.gerrit.server.change.Abandon.java

@Override
public Object apply(ChangeResource req, Input input)
        throws BadRequestException, AuthException, ResourceConflictException, Exception {
    ChangeControl control = req.getControl();
    IdentifiedUser caller = (IdentifiedUser) control.getCurrentUser();
    Change change = req.getChange();/*  w  ww .ja  v a2 s  .  co m*/
    if (!control.canAbandon()) {
        throw new AuthException("abandon not permitted");
    } else if (!change.getStatus().isOpen()) {
        throw new ResourceConflictException("change is " + status(change));
    }

    ChangeMessage message;
    ReviewDb db = dbProvider.get();
    db.changes().beginTransaction(change.getId());
    try {
        change = db.changes().atomicUpdate(change.getId(), new AtomicUpdate<Change>() {
            @Override
            public Change update(Change change) {
                if (change.getStatus().isOpen()) {
                    change.setStatus(Change.Status.ABANDONED);
                    ChangeUtil.updated(change);
                    return change;
                }
                return null;
            }
        });
        if (change == null) {
            throw new ResourceConflictException(
                    "change is " + status(db.changes().get(req.getChange().getId())));
        }
        message = newMessage(input, caller, change);
        db.changeMessages().insert(Collections.singleton(message));
        new ApprovalsUtil(db).syncChangeStatus(change);
        db.commit();
    } finally {
        db.rollback();
    }

    indexer.index(change);
    try {
        ReplyToChangeSender cm = abandonedSenderFactory.create(change);
        cm.setFrom(caller.getAccountId());
        cm.setChangeMessage(message);
        cm.send();
    } catch (Exception e) {
        log.error("Cannot email update for change " + change.getChangeId(), e);
    }
    hooks.doChangeAbandonedHook(change, caller.getAccount(), db.patchSets().get(change.currentPatchSetId()),
            Strings.emptyToNull(input.message), db);
    return json.format(change);
}

From source file:com.reprezen.swagedit.json.references.JsonReference.java

private static JsonPointer createPointer(String text) {
    if (Strings.emptyToNull(text) == null) {
        return JsonPointer.compile("");
    }//ww  w .jav  a 2 s . c o m

    if (text.startsWith("#")) {
        text = text.substring(1);
    }
    return JsonPointer.compile(text);
}

From source file:org.eclipse.buildship.ui.preferences.GradleWorkbenchPreferencePage.java

private String getResolvedGradleUserHome() {
    String gradleUserHomeExpression = Strings.emptyToNull(this.gradleUserHomeText.getText());

    String gradleUserHomeResolved = null;
    try {/*from   w  w  w .  j  av  a2  s . c o  m*/
        gradleUserHomeResolved = ExpressionUtils.decode(gradleUserHomeExpression);
    } catch (CoreException e) {
        setErrorMessage(
                NLS.bind(LaunchMessages.ErrorMessage_CannotResolveExpression_0, gradleUserHomeExpression));
        setValid(false);
    }
    return gradleUserHomeResolved;
}

From source file:ru.org.linux.user.RegisterController.java

@RequestMapping(value = "/register.jsp", method = RequestMethod.POST)
public ModelAndView doRegister(HttpServletRequest request, @Valid @ModelAttribute("form") RegisterRequest form,
        Errors errors, @RequestParam(required = false) String oldpass) throws Exception {
    HttpSession session = request.getSession();
    Template tmpl = Template.getTemplate(request);

    boolean changeMode = "change".equals(request.getParameter("mode"));

    String nick;//  ww  w.j a  v  a2 s  .  c om

    if (changeMode) {
        if (!tmpl.isSessionAuthorized()) {
            throw new AccessViolationException("Not authorized");
        }

        nick = tmpl.getNick();
    } else {
        nick = form.getNick();

        if (Strings.isNullOrEmpty(nick)) {
            errors.rejectValue("nick", null, "  nick");
        }

        if (nick != null && !StringUtil.checkLoginName(nick)) {
            errors.rejectValue("nick", null, " ? ?");
        }

        if (nick != null && nick.length() > User.MAX_NICK_LENGTH) {
            errors.rejectValue("nick", null, "?  ? ?");
        }
    }

    String password = Strings.emptyToNull(form.getPassword());

    if (password != null && password.equalsIgnoreCase(nick)) {
        errors.reject(null, "   ? ? ");
    }

    InternetAddress mail = null;

    if (Strings.isNullOrEmpty(form.getEmail())) {
        errors.rejectValue("email", null, "?  e-mail");
    } else {
        try {
            mail = new InternetAddress(form.getEmail());
        } catch (AddressException e) {
            errors.rejectValue("email", null, "? e-mail: " + e.getMessage());
        }
    }

    String url = null;

    if (!Strings.isNullOrEmpty(form.getUrl())) {
        url = URLUtil.fixURL(form.getUrl());
    }

    if (!changeMode) {
        if (Strings.isNullOrEmpty(password)) {
            errors.reject(null, "    ?");
        }
    }

    String name = Strings.emptyToNull(form.getName());

    if (name != null) {
        name = StringUtil.escapeHtml(name);
    }

    String town = null;

    if (!Strings.isNullOrEmpty(form.getTown())) {
        town = StringUtil.escapeHtml(form.getTown());
    }

    String info = null;

    if (!Strings.isNullOrEmpty(form.getInfo())) {
        info = StringUtil.escapeHtml(form.getInfo());
    }

    if (!changeMode && !errors.hasErrors()) {
        captcha.checkCaptcha(request, errors);

        if (session.getAttribute("register-visited") == null) {
            logger.info("Flood protection (not visited register.jsp) " + request.getRemoteAddr());
            errors.reject(null, "? ,   ");
        }
    }

    ipBlockDao.checkBlockIP(request.getRemoteAddr(), errors);

    boolean emailChanged = false;

    if (changeMode) {
        User user = userDao.getUser(nick);

        if (!user.matchPassword(oldpass)) {
            errors.reject(null, "? ");
        }

        user.checkAnonymous();

        String newEmail = null;

        if (mail != null) {
            if (user.getEmail() != null && user.getEmail().equals(form.getEmail())) {
                newEmail = null;
            } else {
                if (userDao.getByEmail(mail.getAddress()) != null) {
                    errors.rejectValue("email", null, " email  ???");
                }

                newEmail = mail.getAddress();

                emailChanged = true;
            }
        }

        if (!errors.hasErrors()) {
            userDao.updateUser(user, name, url, newEmail, town, password, info);

            if (emailChanged) {
                sendEmail(tmpl, user.getNick(), mail.getAddress(), false);
            }
        } else {
            return new ModelAndView("register-update");
        }
    } else {
        if (userDao.isUserExists(nick)) {
            errors.rejectValue("nick", null,
                    " " + nick + "  ??");
        }

        if (url != null && !URLUtil.isUrl(url)) {
            errors.rejectValue("url", null, "? URL");
        }

        if (mail != null && userDao.getByEmail(mail.getAddress()) != null) {
            errors.rejectValue("email", null,
                    " ?  e-mail  ?. "
                            + "?    ? , ??  ??? ?");
        }

        if (!errors.hasErrors()) {
            int userid = userDao.createUser(name, nick, password, url, mail, town, info);

            String logmessage = "?  " + nick + " (id="
                    + userid + ") " + LorHttpUtils.getRequestIP(request);
            logger.info(logmessage);

            sendEmail(tmpl, nick, mail.getAddress(), true);
        } else {
            return new ModelAndView("register");
        }
    }

    if (changeMode) {
        if (emailChanged) {
            String msg = " ?  ?.  ? ?   ? email.";

            return new ModelAndView("action-done", "message", msg);
        } else {
            return new ModelAndView(new RedirectView("/people/" + nick + "/profile"));
        }
    } else {
        return new ModelAndView("action-done", "message",
                " ?  ?.  ? ?  .");
    }
}

From source file:org.dcache.alarms.server.LogEntryServerWrapper.java

public void setDefinitions(String definitionsPath) {
    this.definitionsPath = Strings.emptyToNull(definitionsPath);
}

From source file:org.haiku.haikudepotserver.multipage.controller.ViewPkgController.java

@RequestMapping(value = "{name}/{repositoryCode}/{major}/{minor}/{micro}/{preRelease}/{revision}/{architectureCode}", method = RequestMethod.GET)
public ModelAndView viewPkg(HttpServletRequest httpServletRequest,
        @PathVariable(value = "repositoryCode") String repositoryCode,
        @PathVariable(value = "name") String pkgName, @PathVariable(value = "major") String major,
        @PathVariable(value = "minor") String minor, @PathVariable(value = "micro") String micro,
        @PathVariable(value = "preRelease") String preRelease,
        @PathVariable(value = "revision") String revisionStr,
        @PathVariable(value = "architectureCode") String architectureCode)
        throws MultipageObjectNotFoundException {

    major = hyphenToNull(major);/*from w w w .j a v  a 2 s  . c  om*/
    minor = hyphenToNull(minor);
    micro = hyphenToNull(micro);
    preRelease = hyphenToNull(preRelease);
    revisionStr = hyphenToNull(revisionStr);

    Integer revision = null == revisionStr ? null : Integer.parseInt(revisionStr);

    ObjectContext context = serverRuntime.newContext();
    Optional<Pkg> pkgOptional = Pkg.tryGetByName(context, pkgName);

    if (!pkgOptional.isPresent()) {
        throw new MultipageObjectNotFoundException(Pkg.class.getSimpleName(), pkgName); // 404
    }

    Architecture architecture = Architecture.tryGetByCode(context, architectureCode).orElseThrow(
            () -> new MultipageObjectNotFoundException(Architecture.class.getSimpleName(), architectureCode));

    Repository repository = Repository.tryGetByCode(context, repositoryCode).orElseThrow(
            () -> new MultipageObjectNotFoundException(Repository.class.getSimpleName(), repositoryCode));

    VersionCoordinates coordinates = new VersionCoordinates(Strings.emptyToNull(major),
            Strings.emptyToNull(minor), Strings.emptyToNull(micro), Strings.emptyToNull(preRelease), revision);

    Optional<PkgVersion> pkgVersionOptional = PkgVersion.getForPkg(context, pkgOptional.get(), repository,
            architecture, coordinates);

    if (!pkgVersionOptional.isPresent() || !pkgVersionOptional.get().getActive()) {
        throw new MultipageObjectNotFoundException(PkgVersion.class.getSimpleName(), pkgName + "...");
    }

    String homeUrl;

    {
        UriComponentsBuilder builder = UriComponentsBuilder.fromPath(MultipageConstants.PATH_MULTIPAGE);
        String naturalLanguageCode = httpServletRequest.getParameter(WebConstants.KEY_NATURALLANGUAGECODE);

        if (!Strings.isNullOrEmpty(naturalLanguageCode)) {
            builder.queryParam(WebConstants.KEY_NATURALLANGUAGECODE, naturalLanguageCode);
        }

        homeUrl = builder.build().toString();
    }

    ViewPkgVersionData data = new ViewPkgVersionData();

    data.setPkgVersion(pkgVersionOptional.get());
    data.setCurrentNaturalLanguage(NaturalLanguageWebHelper.deriveNaturalLanguage(context, httpServletRequest));
    data.setHomeUrl(homeUrl);
    data.setIsSourceAvailable(hasSource(context, pkgVersionOptional.get()));

    ModelAndView result = new ModelAndView("multipage/viewPkgVersion");
    result.addObject("data", data);

    return result;

}

From source file:org.killbill.billing.plugin.analytics.reports.ReportsUserApi.java

public ReportsUserApi(final OSGIKillbillLogService logService, final OSGIKillbillAPI killbillAPI,
        final OSGIKillbillDataSource osgiKillbillDataSource,
        final OSGIConfigPropertiesService osgiConfigPropertiesService, final EmbeddedDB.DBEngine dbEngine,
        final ReportsConfiguration reportsConfiguration, final JobsScheduler jobsScheduler) {
    this.killbillAPI = killbillAPI;
    this.dbEngine = dbEngine;
    this.reportsConfiguration = reportsConfiguration;
    this.jobsScheduler = jobsScheduler;
    dbi = BusinessDBIProvider.get(osgiKillbillDataSource.getDataSource());

    final String nbThreadsMaybeNull = Strings
            .emptyToNull(osgiConfigPropertiesService.getString(ANALYTICS_REPORTS_NB_THREADS_PROPERTY));
    this.dbiThreadsExecutor = BusinessExecutor.newCachedThreadPool(
            nbThreadsMaybeNull == null ? 10 : Integer.valueOf(nbThreadsMaybeNull), "osgi-analytics-dashboard");

    this.sqlMetadata = new Metadata(Sets.<String>newHashSet(
            Iterables.transform(reportsConfiguration.getAllReportConfigurations(null).values(),
                    new Function<ReportsConfigurationModelDao, String>() {
                        @Override
                        public String apply(final ReportsConfigurationModelDao reportConfiguration) {
                            return reportConfiguration.getSourceTableName();
                        }//from  ww w. j a v  a2 s.c  om
                    })),
            osgiKillbillDataSource.getDataSource(), logService);
}