Java Code Examples for com.google.common.base.Strings#nullToEmpty()

The following examples show how to use com.google.common.base.Strings#nullToEmpty() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MqttMessageFactory.java    From lannister with Apache License 2.0 6 votes vote down vote up
public static MqttConnectMessage connect(ConnectOptions options) {
	MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.CONNECT, false, MqttQoS.AT_MOST_ONCE, false,
			10);
	MqttConnectVariableHeader variableHeader = new MqttConnectVariableHeader(options.version().protocolName(),
			options.version().protocolLevel(), options.userName() != null, options.password() != null,
			options.will() == null ? false : options.will().isRetain(),
			options.will() == null ? 0 : options.will().qos().value(), options.will() != null,
			options.cleanSession(), options.keepAliveTimeSeconds());

	MqttConnectPayload payload = new MqttConnectPayload(Strings.nullToEmpty(options.clientId()),
			options.will() == null ? "" : options.will().topicName(),
			options.will() == null ? "" : new String(options.will().message(), CharsetUtil.UTF_8),
			Strings.nullToEmpty(options.userName()), Strings.nullToEmpty(options.password()));

	return new MqttConnectMessage(fixedHeader, variableHeader, payload);
}
 
Example 2
Source File: AbstractSREInstall.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Override
public void setBootstrap(String bootstrap) {
	if (isDirty()) {
		setDirty(false);
		resolveDirtyFields(true);
	}
	final String normalizedName = Strings.nullToEmpty(bootstrap);
	if (!normalizedName.equals(Strings.nullToEmpty(this.bootstrap))) {
		final PropertyChangeEvent event = new PropertyChangeEvent(
				this, ISREInstallChangedListener.PROPERTY_BOOTSTRAP, this.bootstrap, normalizedName);
		this.bootstrap = normalizedName;
		if (this.notify) {
			SARLRuntime.fireSREChanged(event);
		}
	}
}
 
Example 3
Source File: ServerManager.java    From qconfig with MIT License 6 votes vote down vote up
@Override
public AppServerConfig getAppServerConfig() {
    if (appConfig == null) {
        synchronized (ServerManager.class) {
            String appCode = Strings.nullToEmpty(appInfoMap.get(APP_CODE_KEY));
            String env = Strings.nullToEmpty(appInfoMap.get(ENV_NAME_KEY));
            int port = Integer.valueOf(appInfoMap.get(PORT_KEY));
            String ip = LocalHostUtil.getLocalHost();
            String profile = env + ":" + Strings.nullToEmpty(appInfoMap.get(APP_PROFILE_KEY));
            String room = Strings.nullToEmpty(appInfoMap.get(APP_ROOM_KEY));
            String token = Strings.nullToEmpty(appInfoMap.get(TOKEN_KEY));
            AppServerType type = AppServerType.valueOf(env);
            appConfig = new AppServerConfig(appCode, env, token, ip, port, type, profile, Strings.nullToEmpty(null),  Strings.nullToEmpty(room));
        }
    }
    return appConfig;
}
 
Example 4
Source File: MixinPreProcessorStandard.java    From Mixin with MIT License 5 votes vote down vote up
private static String getDynamicInfo(String targetType, AnnotationNode annotation) {
    String description = Strings.nullToEmpty(Annotations.<String>getValue(annotation));
    Type upstream = Annotations.<Type>getValue(annotation, "mixin");
    if (upstream != null) {
        description = String.format("{%s} %s", upstream.getClassName(), description).trim();
    }
    return description.length() > 0 ? String.format(" %s is @Dynamic(%s)", targetType, description) : "";
}
 
Example 5
Source File: MySqlNodeEffectors.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Override
public Void call(ConfigBag parameters) {
    String path = parameters.get(PATH);
    String additionalOptions = Strings.nullToEmpty(parameters.get(ADDITIONAL_OPTIONS));
    //TODO additionalOptions, path are not sanitized and are coming from the user.
    //Should we try to sanitize (potentially limiting the range of possible inputs),
    //or just assume the user has full machine access anyway?
    ((MySqlNodeImpl)entity()).getDriver().dumpDatabase(additionalOptions, path);
    return null;
}
 
Example 6
Source File: FloatWindowService.java    From FloatWindow with Apache License 2.0 5 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    String action = Strings.nullToEmpty(intent.getAction());
    switch (action) {
        case ACTION_CHECK_PERMISSION_AND_TRY_ADD:
            //对沙雕Vivo做特殊处理
            if (RomUtils.isVivoRom()) {
                mHandler.sendEmptyMessageDelayed(HANDLER_DETECT_PERMISSION, 1000);
            } else {
                mHandler.sendEmptyMessage(HANDLER_DETECT_PERMISSION);
            }
            break;
        case ACTION_FULL_SCREEN_TOUCH_ABLE:
            showFullTouchWindow();
            break;
        case ACTION_FULL_SCREEN_TOUCH_DISABLE:
            showFullTouchDisableWindow();
            break;
        case ACTION_NOT_FULL_SCREEN_TOUCH_ABLE:
            showNotFullTouchWindow();
            break;
        case ACTION_NOT_FULL_SCREEN_TOUCH_DISABLE:
            showNotFullTouchDisableWindow();
            break;

        case ACTION_INPUT:
            showInputWindow();
            break;
        case ACTION_KILL:
            stopSelf();
            break;
    }
    return START_STICKY;
}
 
Example 7
Source File: MySqlClusterIntegrationTest.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
private boolean fileExists(MySqlNode node, String binLogName) {
    String dataDir = Strings.nullToEmpty(node.getConfig(MySqlNode.DATA_DIR));
    String path = Os.mergePathsUnix(dataDir, binLogName);
    String cmd = BashCommands.chain(
            "cd $RUN_DIR",
            BashCommands.requireTest(String.format("-f \"%s\"", path), "File " + path + " doesn't exist."));
    String summary = "Check if file " + path + " exists";
    SshMachineLocation machine = EffectorTasks.getSshMachine(node);
    return Entities.submit(node, SshTasks.newSshExecTaskFactory(machine, cmd)
            .allowingNonZeroExitCode()
            .environmentVariable("RUN_DIR", node.getAttribute(SoftwareProcess.RUN_DIR))
            .summary(summary)
            .allowingNonZeroExitCode()).asTask().getUnchecked() == 0;
}
 
Example 8
Source File: SubPathPrefixes.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
/** Get sub-path for particular Volume Mount in a particular workspace */
private String getVolumeMountSubpath(
    VolumeMount volumeMount, String volumeName, String workspaceId, String machineName) {
  String volumeMountSubPath = Strings.nullToEmpty(volumeMount.getSubPath());
  if (!volumeMountSubPath.startsWith("/")) {
    volumeMountSubPath = '/' + volumeMountSubPath;
  }

  return getVolumeSubpath(workspaceId, volumeName, machineName) + volumeMountSubPath;
}
 
Example 9
Source File: EscapedParameter.java    From firing-range with Apache License 2.0 5 votes vote down vote up
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
  String echoedParam = Strings.nullToEmpty(request.getParameter(ECHOED_PARAM));
  String template = Templates.getTemplate(request, getClass());
  Escaper.EscapeMode escaper =
      Escaper.EscapeMode.valueOf(Splitter.on('/').splitToList(request.getPathInfo()).get(2));
  String escapedParam = escaper.escape(echoedParam);
  Responses.sendXssed(response, Templates.replacePayload(template, escapedParam));
}
 
Example 10
Source File: Transaction.java    From glowroot with Apache License 2.0 5 votes vote down vote up
void addAttribute(String name, @Nullable String value) {
    synchronized (attributesLock) {
        if (attributes == null) {
            // no race condition here since only transaction thread calls addAttribute()
            attributes = HashMultimap.create(ATTRIBUTE_KEYS_INITIAL_CAPACITY, 1);
        }
        String val = Strings.nullToEmpty(value);
        Collection<String> values = attributes.get(name);
        if (values.size() < ATTRIBUTE_VALUES_PER_KEY_LIMIT) {
            values.add(val);
        }
    }
}
 
Example 11
Source File: DownloadFileParser.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
private static <T extends Enum<T>> T optEnum(
    final Map<?, ?> jsonObject, final Class<T> type, final String name, final T defaultValue) {
  checkNotNull(jsonObject);
  checkNotNull(type);
  checkNotNull(name);
  checkNotNull(defaultValue);

  final String valueName = Strings.nullToEmpty((String) jsonObject.get(name));
  return valueName.isEmpty() ? defaultValue : Enum.valueOf(type, valueName);
}
 
Example 12
Source File: BuckEventAndroidLogger.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public void error(@Nullable Throwable throwable, @Nullable String errorFormat, Object... args) {
  String message = Strings.nullToEmpty(errorFormat);
  if (throwable == null) {
    eventBus.post(ConsoleEvent.severe(message, args));
  } else {
    eventBus.post(ThrowableConsoleEvent.create(throwable, message, args));
  }
}
 
Example 13
Source File: YoungAndroidProjectService.java    From appinventor-extensions with Apache License 2.0 5 votes vote down vote up
/**
 * Returns project settings that can be used when creating a new project.
 */
public static String getProjectSettings(String icon, String vCode, String vName,
  String useslocation, String aName, String sizing, String showListsAsJson, String tutorialURL, String subsetJSON,
  String actionBar, String theme, String primaryColor, String primaryColorDark, String accentColor) {
  icon = Strings.nullToEmpty(icon);
  vCode = Strings.nullToEmpty(vCode);
  vName = Strings.nullToEmpty(vName);
  useslocation = Strings.nullToEmpty(useslocation);
  sizing = Strings.nullToEmpty(sizing);
  aName = Strings.nullToEmpty(aName);
  showListsAsJson = Strings.nullToEmpty(showListsAsJson);
  tutorialURL = Strings.nullToEmpty(tutorialURL);
  subsetJSON = Strings.nullToEmpty(subsetJSON);
  actionBar = Strings.nullToEmpty(actionBar);
  theme = Strings.nullToEmpty(theme);
  primaryColor = Strings.nullToEmpty(primaryColor);
  primaryColorDark = Strings.nullToEmpty(primaryColorDark);
  accentColor = Strings.nullToEmpty(accentColor);
  return "{\"" + SettingsConstants.PROJECT_YOUNG_ANDROID_SETTINGS + "\":{" +
      "\"" + SettingsConstants.YOUNG_ANDROID_SETTINGS_ICON + "\":\"" + icon +
      "\",\"" + SettingsConstants.YOUNG_ANDROID_SETTINGS_VERSION_CODE + "\":\"" + vCode +
      "\",\"" + SettingsConstants.YOUNG_ANDROID_SETTINGS_VERSION_NAME + "\":\"" + vName +
      "\",\"" + SettingsConstants.YOUNG_ANDROID_SETTINGS_USES_LOCATION + "\":\"" + useslocation +
      "\",\"" + SettingsConstants.YOUNG_ANDROID_SETTINGS_APP_NAME + "\":\"" + aName +
      "\",\"" + SettingsConstants.YOUNG_ANDROID_SETTINGS_SIZING + "\":\"" + sizing +
      "\",\"" + SettingsConstants.YOUNG_ANDROID_SETTINGS_SHOW_LISTS_AS_JSON + "\":\"" + showListsAsJson +
      "\",\"" + SettingsConstants.YOUNG_ANDROID_SETTINGS_TUTORIAL_URL + "\":\"" + tutorialURL +
      "\",\"" + SettingsConstants.YOUNG_ANDROID_SETTINGS_BLOCK_SUBSET + "\":\"" + subsetJSON +
      "\",\"" + SettingsConstants.YOUNG_ANDROID_SETTINGS_ACTIONBAR + "\":\"" + actionBar +
      "\",\"" + SettingsConstants.YOUNG_ANDROID_SETTINGS_THEME + "\":\"" + theme +
      "\",\"" + SettingsConstants.YOUNG_ANDROID_SETTINGS_PRIMARY_COLOR + "\":\"" + primaryColor +
      "\",\"" + SettingsConstants.YOUNG_ANDROID_SETTINGS_PRIMARY_COLOR_DARK + "\":\"" + primaryColorDark +
      "\",\"" + SettingsConstants.YOUNG_ANDROID_SETTINGS_ACCENT_COLOR + "\":\"" + accentColor +
      "\"}}";
}
 
Example 14
Source File: GuiComponentLabel.java    From OpenModsLib with MIT License 4 votes vote down vote up
public void setText(String text) {
	this.formattedText = null;
	this.text = Strings.nullToEmpty(text);
}
 
Example 15
Source File: FlexDeployPreferences.java    From google-cloud-eclipse with Apache License 2.0 4 votes vote down vote up
public void setAppYamlPath(String appYamlPath) {
  this.appYamlPath = Strings.nullToEmpty(appYamlPath);
}
 
Example 16
Source File: Compiler.java    From appinventor-extensions with Apache License 2.0 4 votes vote down vote up
private boolean prepareApplicationIcon(File outputPngFile, List<File> mipmapDirectories, List<Integer> standardICSizes, List<Integer> foregroundICSizes) {
  String userSpecifiedIcon = Strings.nullToEmpty(project.getIcon());
  try {
    BufferedImage icon;
    if (!userSpecifiedIcon.isEmpty()) {
      File iconFile = new File(project.getAssetsDirectory(), userSpecifiedIcon);
      icon = ImageIO.read(iconFile);
      if (icon == null) {
        // This can happen if the iconFile isn't an image file.
        // For example, icon is null if the file is a .wav file.
        // TODO(lizlooney) - This happens if the user specifies a .ico file. We should
        // fix that.
        userErrors.print(String.format(ICON_ERROR, userSpecifiedIcon));
        return false;
      }
    } else {
      // Load the default image.
      icon = ImageIO.read(Compiler.class.getResource(DEFAULT_ICON));
    }

    BufferedImage roundIcon = produceRoundIcon(icon);
    BufferedImage roundRectIcon = produceRoundedCornerIcon(icon);
    BufferedImage foregroundIcon = produceForegroundImageIcon(icon);

    // For each mipmap directory, create all types of ic_launcher photos with respective mipmap sizes
    for(int i=0; i < mipmapDirectories.size(); i++){
      File mipmapDirectory = mipmapDirectories.get(i);
      Integer standardSize = standardICSizes.get(i);
      Integer foregroundSize = foregroundICSizes.get(i);

      BufferedImage round = resizeImage(roundIcon,standardSize,standardSize);
      BufferedImage roundRect = resizeImage(roundRectIcon,standardSize,standardSize);
      BufferedImage foreground = resizeImage(foregroundIcon,foregroundSize,foregroundSize);

      File roundIconPng = new File(mipmapDirectory,"ic_launcher_round.png");
      File roundRectIconPng = new File(mipmapDirectory,"ic_launcher.png");
      File foregroundPng = new File(mipmapDirectory,"ic_launcher_foreground.png");

      ImageIO.write(round, "png", roundIconPng);
      ImageIO.write(roundRect, "png", roundRectIconPng);
      ImageIO.write(foreground, "png", foregroundPng);
    }
    ImageIO.write(icon, "png", outputPngFile);
  } catch (Exception e) {
    e.printStackTrace();
    // If the user specified the icon, this is fatal.
    if (!userSpecifiedIcon.isEmpty()) {
      userErrors.print(String.format(ICON_ERROR, userSpecifiedIcon));
      return false;
    }
  }

  return true;
}
 
Example 17
Source File: S3ProxyHandler.java    From s3proxy with Apache License 2.0 4 votes vote down vote up
public S3ProxyHandler(final BlobStore blobStore,
        AuthenticationType authenticationType, final String identity,
        final String credential, @Nullable String virtualHost,
        long v4MaxNonChunkedRequestSize, boolean ignoreUnknownHeaders,
        CrossOriginResourceSharing corsRules, final String servicePath,
        int maximumTimeSkew) {
    if (authenticationType != AuthenticationType.NONE) {
        anonymousIdentity = false;
        blobStoreLocator = new BlobStoreLocator() {
            @Nullable
            @Override
            public Map.Entry<String, BlobStore> locateBlobStore(
                    String identityArg, String container, String blob) {
                if (!identity.equals(identityArg)) {
                    return null;
                }
                return Maps.immutableEntry(credential, blobStore);
            }
        };
    } else {
        anonymousIdentity = true;
        final Map.Entry<String, BlobStore> anonymousBlobStore =
                Maps.immutableEntry(null, blobStore);
        blobStoreLocator = new BlobStoreLocator() {
            @Override
            public Map.Entry<String, BlobStore> locateBlobStore(
                    String identityArg, String container, String blob) {
                return anonymousBlobStore;
            }
        };
    }
    this.authenticationType = authenticationType;
    this.virtualHost = Optional.fromNullable(virtualHost);
    this.v4MaxNonChunkedRequestSize = v4MaxNonChunkedRequestSize;
    this.ignoreUnknownHeaders = ignoreUnknownHeaders;
    this.corsRules = corsRules;
    this.defaultBlobStore = blobStore;
    xmlOutputFactory.setProperty("javax.xml.stream.isRepairingNamespaces",
            Boolean.FALSE);
    this.servicePath = Strings.nullToEmpty(servicePath);
    this.maximumTimeSkew = maximumTimeSkew;
}
 
Example 18
Source File: WChatOutputEvent.java    From ForgeWurst with GNU General Public License v3.0 4 votes vote down vote up
public WChatOutputEvent(String message)
{
	setMessage(message);
	originalMessage = Strings.nullToEmpty(message);
}
 
Example 19
Source File: CallbackInjectionInfo.java    From Mixin with MIT License 4 votes vote down vote up
@Override
public String getSliceId(String id) {
    return Strings.nullToEmpty(id);
}
 
Example 20
Source File: DeployPreferences.java    From google-cloud-eclipse with Apache License 2.0 4 votes vote down vote up
public void setVersion(String version) {
  this.version = Strings.nullToEmpty(version);
}