Java 类com.google.common.base.Strings 实例源码

项目:Reer    文件:ShortExceptionFormatter.java   
private void printException(TestDescriptor descriptor, Throwable exception, boolean cause, int indentLevel, StringBuilder builder) {
    String indent = Strings.repeat(INDENT, indentLevel);
    builder.append(indent);
    if (cause) {
        builder.append("Caused by: ");
    }
    String className = exception instanceof PlaceholderException
            ? ((PlaceholderException) exception).getExceptionClassName() : exception.getClass().getName();
    builder.append(className);

    StackTraceFilter filter = new StackTraceFilter(new ClassMethodNameStackTraceSpec(descriptor.getClassName(), null));
    List<StackTraceElement> stackTrace = filter.filter(exception);
    if (stackTrace.size() > 0) {
        StackTraceElement element = stackTrace.get(0);
        builder.append(" at ");
        builder.append(element.getFileName());
        builder.append(':');
        builder.append(element.getLineNumber());
    }
    builder.append('\n');

    if (testLogging.getShowCauses() && exception.getCause() != null) {
        printException(descriptor, exception.getCause(), true, indentLevel + 1, builder);
    }
}
项目:apollo-custom    文件:NotificationControllerV2.java   
private Map<String, ApolloConfigNotification> filterNotifications(String appId,
                                                                  List<ApolloConfigNotification> notifications) {
  Map<String, ApolloConfigNotification> filteredNotifications = Maps.newHashMap();
  for (ApolloConfigNotification notification : notifications) {
    if (Strings.isNullOrEmpty(notification.getNamespaceName())) {
      continue;
    }
    //strip out .properties suffix
    String originalNamespace = namespaceUtil.filterNamespaceName(notification.getNamespaceName());
    notification.setNamespaceName(originalNamespace);
    //fix the character case issue, such as FX.apollo <-> fx.apollo
    String normalizedNamespace = namespaceUtil.normalizeNamespace(appId, originalNamespace);

    // in case client side namespace name has character case issue and has difference notification ids
    // such as FX.apollo = 1 but fx.apollo = 2, we should let FX.apollo have the chance to update its notification id
    // which means we should record FX.apollo = 1 here and ignore fx.apollo = 2
    if (filteredNotifications.containsKey(normalizedNamespace) &&
        filteredNotifications.get(normalizedNamespace).getNotificationId() < notification.getNotificationId()) {
      continue;
    }

    filteredNotifications.put(normalizedNamespace, notification);
  }
  return filteredNotifications;
}
项目:qpp-conversion-tool    文件:ConversionEntry.java   
/**
 * Produce collection of files found within the given path
 *
 * @param path A file location.
 * @return The list of files at the file location.
 */
static Collection<Path> checkPath(String path) {
    Collection<Path> existingFiles = new LinkedList<>();

    if (Strings.isNullOrEmpty(path)) {
        return existingFiles;
    }
    if (path.contains("*")) {
        return manyPath(path);
    }

    Path file = fileSystem.getPath(path);
    if (Files.exists(file)) {
        existingFiles.add(file);
    } else {
        DEV_LOG.error(FILE_DOES_NOT_EXIST, file.toAbsolutePath());
    }
    return existingFiles;
}
项目:commelina    文件:NioSocketEventHandlerForAkka.java   
@Override
public CompletableFuture<Long> onLogin(ChannelHandlerContext ctx, SocketASK ask) {
    // 整个消息就是 token
    ByteString tokenArg = ask.getBody().getArgs(0);
    if (tokenArg == null) {
        logger.info("Token arg must be input.");
        return null;
    }
    String token = tokenArg.toStringUtf8();
    if (Strings.isNullOrEmpty(token)) {
        logger.info("Token arg must be input.");
        return null;
    }
    return CompletableFuture.supplyAsync(() -> {
        String parseToken = new String(BaseEncoding.base64Url().decode(token));
        List<String> tokenChars = Splitter.on('|').splitToList(parseToken);
        return Long.valueOf(tokenArg.toStringUtf8());
    });
}
项目:Telephoto    文件:TelegramService.java   
@Override
public void sendMessageToAll(final List<IncomingMessage> incomingMessageList) {
    final Set<Prefs.UserPrefs> subscribers = PrefsController.instance.getPrefs().getEventListeners();
    es.submit(new Runnable() {
        @Override
        public void run() {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(botService.getString(com.rai220.securityalarmbot.R.string.incoming_messages));
            for (IncomingMessage message : incomingMessageList) {
                stringBuilder.append(message.getPhone());
                if (!Strings.isNullOrEmpty(message.getName())) {
                    stringBuilder.append(" (").append(message.getName()).append(")");
                }
                stringBuilder.append(": \"").append(message.getMessage()).append("\"\n");
            }

            for (final Prefs.UserPrefs user : subscribers) {
                bot.execute(new SendMessage(user.lastChatId, stringBuilder.toString()));
            }
        }
    });
}
项目:wall-t    文件:TileViewModel.java   
@Subscribe
public final void updateTileViewModel( final BuildTypeData data ) {
    if ( data != _buildTypeData )
        return;

    Platform.runLater( ( ) -> {
        _displayedName.set( Strings.isNullOrEmpty( data.getAliasName( ) ) ? data.getName( ) : data.getAliasName( ) );
        _running.setValue( data.hasRunningBuild( ) );
        _queued.setValue( data.isQueued( ) );

        updateLastFinishedDate( );
        updateTimeLeft( );
        updatePercentageComplete( );
        updateBackground( );
        updateIcon( );
    } );
}
项目:Equella    文件:CustomerFilter.java   
@Override
public FilterResult filterRequest(HttpServletRequest request, HttpServletResponse response) throws IOException,
    ServletException
{
    if( CurrentInstitution.get() != null )
    {
        String path = (request.getServletPath() + Strings.nullToEmpty(request.getPathInfo())).substring(1);

        // Disallow overriding of CSS files supplied by plugins. Clients
        // should always override CSS rules in customer.css
        if( CSS_PROVIDED_BY_PLUGIN.matcher(path).matches() )
        {
            return FilterResult.FILTER_CONTINUE;
        }

        // Remove the version number from the path which is there to
        // facilitate long expiry dates.
        final Matcher m = REMOVE_VERSION_FROM_PATH.matcher(path);
        if( m.matches() )
        {
            path = "p/r/" + m.group(1);
        }

        CustomisationFile customFile = new CustomisationFile();
        if( fileService.fileExists(customFile, path) )
        {
            String mimeType = mimeTypeService.getMimeTypeForFilename(path);
            FileContentStream contentStream = fileService.getContentStream(customFile, path, mimeType);
            contentStreamWriter.outputStream(request, response, contentStream);
            response.flushBuffer();
        }
    }
    return FilterResult.FILTER_CONTINUE;
}
项目:TextHIN    文件:Master.java   
void addNewExample(Example origEx) {
  // Create the new example, but only add relevant information.
  Example ex = new Example.Builder()
      .setId(origEx.id)
      .setUtterance(origEx.utterance)
      .setContext(origEx.context)
      .setTargetFormula(origEx.targetFormula)
      .setTargetValue(origEx.targetValue)
      .createExample();

  if (!Strings.isNullOrEmpty(opts.newExamplesPath)) {
    LogInfo.begin_track("Adding new example");
    Dataset.appendExampleToFile(opts.newExamplesPath, ex);
    LogInfo.end_track();
  }

  if (opts.onlineLearnExamples) {
    LogInfo.begin_track("Updating parameters");
    learner.onlineLearnExample(origEx);
    if (!Strings.isNullOrEmpty(opts.newParamsPath))
      builder.params.write(opts.newParamsPath);
    LogInfo.end_track();
  }
}
项目:Sound.je    文件:Occurrence.java   
@Override
public String getUrl() {
    String name = "e";
    try {
        name = URLEncoder.encode(getEvent().map(Event::getName)
                .map(newName -> newName.replace(" ", "_"))
                .map(newName -> newName.replace("/", ""))
                .map(newName -> Strings.padStart(newName, 1, 'e'))
                .orElse("#"), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        logger.info("[Occurrence] [getUrl] Failure To Encode URL", e);
    }

    return String.format(
            "/Events/%s/%s?startTime=%s",
            getEvent().map(Event::getIdBase64).orElse(""),
            name, // uuidToBase64(getEvent().getId()),
            String.valueOf(getStartTime().getMillis())
    );
}
项目:BaseClient    文件:GuiOverlayDebug.java   
protected void renderDebugInfoLeft()
{
    List list = this.call();

    for (int i = 0; i < list.size(); ++i)
    {
        String s = (String)list.get(i);

        if (!Strings.isNullOrEmpty(s))
        {
            int j = this.fontRenderer.FONT_HEIGHT;
            int k = this.fontRenderer.getStringWidth(s);
            boolean flag = true;
            int l = 2 + j * i;
            drawRect(1, l - 1, 2 + k + 1, l + j - 1, -1873784752);
            this.fontRenderer.drawString(s, 2, l, 14737632);
        }
    }
}
项目:dremio-oss    文件:FileSelection.java   
/**
 * Creates a {@link FileSelection selection} with the given file statuses and selection root.
 *
 * @param statuses  list of file statuses
 * @param root  root path for selections
 *
 * @return  null if creation of {@link FileSelection} fails with an {@link IllegalArgumentException}
 *          otherwise a new selection.
 *
 */
private static FileSelection create(StatusType status, final ImmutableList<FileStatus> statuses, final String root) {
  if (statuses == null || statuses.size() == 0) {
    return null;
  }

  final String selectionRoot;
  if (Strings.isNullOrEmpty(root)) {
    throw new IllegalArgumentException("Selection root is null or empty" + root);
  }
  final Path rootPath = handleWildCard(root);
  final URI uri = statuses.get(0).getPath().toUri();
  final Path path = new Path(uri.getScheme(), uri.getAuthority(), rootPath.toUri().getPath());
  selectionRoot = Path.getPathWithoutSchemeAndAuthority(path).toString();
  return new FileSelection(status, statuses, selectionRoot);
}
项目:ja-micro    文件:Topic.java   
public static Topic serviceInbox(@NotNull String serviceName, String inboxName) {
    StringBuilder topic = new StringBuilder();
    topic.append("inbox");

    if (!Strings.isNullOrEmpty(inboxName)) {
        topic.append("_");
        topic.append(inboxName);
    }

    if (Strings.isNullOrEmpty(serviceName)) {
        throw new IllegalArgumentException("service name must not be null or empty");
    }

    topic.append("-");
    topic.append(serviceName);


    return new Topic(topic.toString());
}
项目:secondbase    文件:SecondBaseLogger.java   
static boolean parametersOk(final String[] keys, final String[] values) {
    if (keys == null || values == null) {
        return false;
    }
    if (keys.length != values.length) {
        return false;
    }
    for (final String key : keys) {
        if (Strings.isNullOrEmpty(key)) {
            return false;
        }
    }
    for (final String value : values) {
        if (Strings.isNullOrEmpty(value)) {
            return false;
        }
    }
    return true;
}
项目:n4js    文件:PositiveAnalyser.java   
private String withLineNumbers(String code) {
    try {
        return CharStreams.readLines(new StringReader(code), new LineProcessor<String>() {

            private final StringBuilder lines = new StringBuilder();
            private int lineNo = 1;

            @Override
            public boolean processLine(String line) throws IOException {
                lines.append(Strings.padStart(String.valueOf(lineNo++), 3, ' ')).append(": ").append(line)
                        .append("\n");
                return true;
            }

            @Override
            public String getResult() {
                return lines.toString();
            }
        });
    } catch (IOException e) {
        throw new IllegalStateException(e.getMessage());
    }
}
项目:Proyecto-DASI    文件:GradleStart.java   
private static void hackNatives()
{
    String paths = System.getProperty("java.library.path");
    String nativesDir = "C:/Users/Sergio/.gradle/caches/minecraft/net/minecraft/natives/1.8";

    if (Strings.isNullOrEmpty(paths))
        paths = nativesDir;
    else
        paths += File.pathSeparator + nativesDir;

    System.setProperty("java.library.path", paths);

    // hack the classloader now.
    try
    {
        final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
        sysPathsField.setAccessible(true);
        sysPathsField.set(null, null);
    }
    catch(Throwable t) {};
}
项目:n4js    文件:RunnerHelper.java   
/**
 * Returns URI to execution module from runtime environment.
 */
public Optional<String> getExecModuleURI(List<IN4JSProject> extendedDeps) {
    List<String> execModules = extendedDeps.stream()
            .filter(p -> ProjectType.RUNTIME_ENVIRONMENT.equals(p.getProjectType()))
            .map(re -> {
                Optional<URI> execModuleAsURI = projectUtils.getExecModuleAsURI(re);
                if (!execModuleAsURI.isPresent()) {
                    return null;
                }
                return compilerHelper.getTargetFileName(re, execModuleAsURI.get(), null);
            })
            .filter(s -> !Strings.isNullOrEmpty(s))
            .collect(Collectors.toList());

    if (execModules.size() >= 1)
        return Optional.of(execModules.get(0));

    return Optional.absent();
}
项目:dremio-oss    文件:ImpersonationUtil.java   
/**
 * Create and return proxy user {@link org.apache.hadoop.security.UserGroupInformation} for give user name.
 *
 * @param proxyUserName Proxy user name (must be valid)
 * @return
 */
public static UserGroupInformation createProxyUgi(String proxyUserName) {
  try {
    if (Strings.isNullOrEmpty(proxyUserName)) {
      throw new IllegalArgumentException("Invalid value for proxy user name");
    }

    // If the request proxy user is same as process user name or same as system user, return the process UGI.
    if (proxyUserName.equals(getProcessUserName()) || SYSTEM_USERNAME.equals(proxyUserName)) {
      return getProcessUserUGI();
    }

    return CACHE.get(new Key(proxyUserName, UserGroupInformation.getLoginUser()));
  } catch (IOException | ExecutionException e) {
    final String errMsg = "Failed to create proxy user UserGroupInformation object: " + e.getMessage();
    logger.error(errMsg, e);
    throw new RuntimeException(errMsg, e);
  }
}
项目:mot-public-api    文件:DatabasePasswordLoader.java   
public String getDbPassword() throws IOException {

        String password = passwordDecrypted;
        String configPasswordEncrypted = getEnvironmentVariable(ConfigKeys.DatabaseEncryptedPassword, false);

        if (Strings.isNullOrEmpty(configPasswordEncrypted)) {
            password = getEnvironmentVariable(ConfigKeys.DatabasePassword);

        } else {
            if (Strings.isNullOrEmpty(password) || !configPasswordEncrypted.equalsIgnoreCase(passwordEncrypted)) {

                password = getEnvironmentVariable(ConfigKeys.DatabaseEncryptedPassword);

                passwordEncrypted = configPasswordEncrypted;
                passwordDecrypted = password;
            }
        }
        return password;
    }
项目:java-binance-api    文件:BinanceConfig.java   
/**
 * Getting variable from one of the multiple sources available
 * @param key variable name
 * @return string result
 */
public String getVariable(String key) {
    // checking VM options for properties
    String sysPropertyValue = System.getProperty(key);
    if (!Strings.isNullOrEmpty(sysPropertyValue)) return sysPropertyValue;

    // checking enviroment variables for properties
    String envPropertyValue = System.getenv(key);
    if (!Strings.isNullOrEmpty(envPropertyValue)) return envPropertyValue;

    // checking resource file for property
    if (prop != null) {
        String property = prop.getProperty(key);
        if (!Strings.isNullOrEmpty(property)) return property;
    }
    return "";
}
项目:apollo-custom    文件:WebContextConfiguration.java   
@Bean
public ServletContextInitializer servletContextInitializer() {

  return new ServletContextInitializer() {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
      String loggingServerIP = portalConfig.cloggingUrl();
      String loggingServerPort = portalConfig.cloggingPort();
      String credisServiceUrl = portalConfig.credisServiceUrl();

      servletContext.setInitParameter("loggingServerIP",
          Strings.isNullOrEmpty(loggingServerIP) ? "" : loggingServerIP);
      servletContext.setInitParameter("loggingServerPort",
          Strings.isNullOrEmpty(loggingServerPort) ? "" : loggingServerPort);
      servletContext.setInitParameter("credisServiceUrl",
          Strings.isNullOrEmpty(credisServiceUrl) ? "" : credisServiceUrl);
    }
  };
}
项目:flow-platform    文件:ControllerUtil.java   
public static <R> List<R> extractParam(String param, Function<String, R> converter) {
    String[] params = param.split(PARAM_DELIMITE);
    List<R> list = new ArrayList<>(params.length);
    for (String item : params) {

        item = item.trim();
        if (Strings.isNullOrEmpty(item)) {
            continue;
        }

        R apply = converter.apply(item);

        if (apply != null) {
            list.add(apply);
        }
    }
    return list;
}
项目:javaide    文件:XmlDocument.java   
/**
 * Decodes a sdk version from either its decimal representation or from a platform code name.
 * @param attributeVersion the sdk version attribute as specified by users.
 * @return the integer representation of the platform level.
 */
private static int getApiLevelFromAttribute(String attributeVersion) {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(attributeVersion));
    if (Character.isDigit(attributeVersion.charAt(0))) {
        return Integer.parseInt(attributeVersion);
    }
    return SdkVersionInfo.getApiByPreviewName(attributeVersion, true);
}
项目:TextHIN    文件:BinaryLexicon.java   
private BinaryLexicon() throws IOException {
  if (Strings.isNullOrEmpty(opts.binaryLexiconFilesPath))
    throw new RuntimeException("Missing unary lexicon file");
  fbFormulasInfo = FbFormulasInfo.getSingleton();
  // if we omit prepositions then the lexicon normalizer does that, otherwise, it is a normalizer that does nothing
  lexiconLoadingNormalizer = new PrepDropNormalizer(); // the alignment lexicon already contains stemmed stuff so just need to drop prepositions
  read(opts.binaryLexiconFilesPath);
}
项目:Reer    文件:DefaultLibraryComponentSelector.java   
@Override
public String getDisplayName() {
    String txt;
    if (Strings.isNullOrEmpty(libraryName)) {
        txt = "project '" + projectPath + "'";
    } else if (Strings.isNullOrEmpty(variant)) {
        txt = "project '" + projectPath + "' library '" + libraryName + "'";
    } else {
        txt = "project '" + projectPath + "' library '" + libraryName + "' binary '" + variant + "'";
    }
    return txt;
}
项目:Reer    文件:ModuleDependency.java   
private boolean scopeEquals(String lhs, String rhs) {
    if ("COMPILE".equals(lhs)) {
        return Strings.isNullOrEmpty(rhs) || "COMPILE".equals(rhs);
    } else if ("COMPILE".equals(rhs)) {
        return Strings.isNullOrEmpty(lhs) || "COMPILE".equals(lhs);
    } else {
        return Objects.equal(lhs, rhs);
    }
}
项目:roboslack    文件:WebHookTokenTests.java   
@ParameterizedTest
@ValueSource(strings = {
        "T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX",
        "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX"})
void testFromString(String input) {
    WebHookToken token = WebHookToken.fromString(input);
    Assertions.assertFalse(Strings.isNullOrEmpty(token.partB()));
    Assertions.assertFalse(Strings.isNullOrEmpty(token.partT()));
    Assertions.assertFalse(Strings.isNullOrEmpty(token.partX()));
    Assertions.assertFalse(Strings.isNullOrEmpty(token.toString()));
}
项目:roboslack    文件:AttachmentTests.java   
public static void assertValid(Attachment attachment) {
    attachment.fields().forEach(FieldTests::assertValid);
    assertFalse(Strings.isNullOrEmpty(attachment.fallback()));
    Optional.ofNullable(attachment.color()).ifPresent(ColorTests::assertValid);
    attachment.pretext().ifPresent(pretext -> assertFalse(Strings.isNullOrEmpty(pretext)));
    Optional.ofNullable(attachment.author()).ifPresent(AuthorTests::assertValid);
    Optional.ofNullable(attachment.title()).ifPresent(TitleTests::assertValid);
    attachment.text().ifPresent(text -> assertFalse(Strings.isNullOrEmpty(text)));
    attachment.imageUrl().ifPresent(imageUrl -> assertFalse(Strings.isNullOrEmpty(imageUrl.toString())));
    attachment.thumbUrl().ifPresent(thumbUrl -> assertFalse(Strings.isNullOrEmpty(thumbUrl.toString())));
    Optional.ofNullable(attachment.footer()).ifPresent(FooterTests::assertValid);
}
项目:instalint    文件:PluginLoader.java   
/**
 * Defines the different classloaders to be created. Number of classloaders can be
 * different than number of plugins.
 */
@VisibleForTesting
Collection<PluginClassLoaderDef> defineClassloaders(Map<String, PluginInfo> infoByKeys) {
  Map<String, PluginClassLoaderDef> classloadersByBasePlugin = new HashMap<>();

  for (PluginInfo info : infoByKeys.values()) {
    String baseKey = basePluginKey(info, infoByKeys);
    PluginClassLoaderDef def = classloadersByBasePlugin.get(baseKey);
    if (def == null) {
      def = new PluginClassLoaderDef(baseKey);
      classloadersByBasePlugin.put(baseKey, def);
    }
    ExplodedPlugin explodedPlugin = jarExploder.explode(info);
    def.addFiles(asList(explodedPlugin.getMain()));
    def.addFiles(explodedPlugin.getLibs());
    def.addMainClass(info.getKey(), info.getMainClass());

    for (String defaultSharedResource : DEFAULT_SHARED_RESOURCES) {
      def.getExportMask().addInclusion(String.format("%s/%s/api/", defaultSharedResource, info.getKey()));
    }

    // The plugins that extend other plugins can only add some files to classloader.
    // They can't change metadata like ordering strategy or compatibility mode.
    if (Strings.isNullOrEmpty(info.getBasePlugin())) {
      def.setSelfFirstStrategy(info.isUseChildFirstClassLoader());
    }
  }
  return classloadersByBasePlugin.values();
}
项目:EchoPet    文件:CommonReflection.java   
private static String combine(String packageName, String className) {
    if (Strings.isNullOrEmpty(packageName)) {
        return className;
    }
    if (Strings.isNullOrEmpty(className)) {
        return packageName;
    }
    return packageName + "." + className;
}
项目:json2java4idea    文件:JsonValidator.java   
@Override
@SuppressWarnings("SimplifiableIfStatement")
public boolean canClose(@Nullable String json) {
    if (Strings.isNullOrEmpty(json)) {
        return false;
    }

    try {
        final JsonElement root = parser.parse(json);
        return !root.isJsonNull() && !root.isJsonPrimitive();
    } catch (JsonParseException e) {
        return false;
    }
}
项目:servicebuilder    文件:ExceptionUtil.java   
public String getContextDescription() {
    StringBuilder sb = new StringBuilder();
    if (request != null) {
        if (! Strings.isNullOrEmpty(request.getRequestURI())) {
            String method = Strings.nullToEmpty(request.getMethod());
            String query = (Strings.isNullOrEmpty(request.getQueryString())) ? "" : "?" + request.getQueryString();
            sb.append(String.format("  uri: %s %s%s\n", method, request.getRequestURI(), query));
        }
        if (request.getUserPrincipal() != null) {
            sb.append(String.format("  userPrincipal: %s\n", request.getUserPrincipal().toString()));
        }
        if (request.getRemoteAddr() != null) {
            sb.append(String.format("  remoteAddr: %s\n", request.getRemoteAddr()));
        }
    } else {
        log.warn("Request context null in exceptionUtil");
    }

    if (headers != null) {
        Joiner joiner = Joiner.on(", ").skipNulls();
        headers.getRequestHeaders().entrySet().forEach(entry -> {
            String headerName = entry.getKey();
            String headerValue = joiner.join(entry.getValue());
            sb.append(String.format("  Header: %s = %s\n", headerName, headerValue));
        });
    }
    return sb.toString();

}
项目:fc-java-sdk    文件:GetFunctionRequest.java   
public void validate() throws ClientException {
    if (Strings.isNullOrEmpty(serviceName)) {
        throw new ClientException("Service name cannot be blank");
    }
    if (Strings.isNullOrEmpty(functionName)) {
        throw new ClientException("Function name cannot be blank");
    }
}
项目:empiria.player    文件:TextEntryGapBase.java   
@Override
public void reset() {
    super.reset();
    if (!Strings.isNullOrEmpty(getTextEntryPresenter().getText())) {
        presenter.setText(StringUtils.EMPTY_STRING);
        updateResponse(false, true);
    }
    sourcelistManager.onUserValueChanged();
}
项目:lemon-fileservice    文件:FileUploadService.java   
/**
    * 上传文件
    */
public String uploadFile(byte[] fileBytes, long size, String path, String ext) throws IOException {
    InputStream inputStream = new ByteArrayInputStream(fileBytes);
    String filePath = Strings.isNullOrEmpty(path) ? "upload": path;
    String fileId = Md5Util.getMD5(fileBytes); //UUID.randomUUID().toString().replace("-", "");
    String fileName = String.format("%s/%s.%s", filePath, fileId, ext);
    this.upload(inputStream, size, fileName);
    return ossConfig.getBaseOssUri() + fileName;
}
项目:verify-matching-service-adapter    文件:SamlAttributeQueryValidator.java   
private void validateIssuer(Issuer issuer) {
    String issuerId = issuer.getValue();
    if (Strings.isNullOrEmpty(issuerId)) {
        SamlValidationSpecificationFailure failure = SamlTransformationErrorFactory.missingIssuer();
        throw new SamlTransformationErrorException(failure.getErrorMessage(), failure.getLogLevel());
    }
}
项目:roboslack    文件:LinkDecorator.java   
@Value.Check
protected final void check() {
    MorePreconditions.checkAtLeastOnePresentAndValid(
            ImmutableList.of("prefix", "suffix"),
            ImmutableList.of(prefix(), suffix()));
    checkArgument(!Strings.isNullOrEmpty(separator()),
            "Separator should be present and valid (non-null, non-empty String)");
}
项目:flow-platform    文件:JobServiceImpl.java   
@Override
public void callback(CmdCallbackQueueItem cmdQueueItem) {
    BigInteger jobId = cmdQueueItem.getJobId();
    Cmd cmd = cmdQueueItem.getCmd();
    Job job = jobDao.get(jobId);

    // if not found job, re enqueue
    if (job == null) {
        throw new NotFoundException("job");
    }

    if (Job.FINISH_STATUS.contains(job.getStatus())) {
        LOGGER.trace("Reject cmd callback since job %s already in finish status", job.getId());
        return;
    }

    if (cmd.getType() == CmdType.CREATE_SESSION) {
        onCreateSessionCallback(job, cmd);
        return;
    }

    if (cmd.getType() == CmdType.RUN_SHELL) {
        String path = cmd.getExtra();
        if (Strings.isNullOrEmpty(path)) {
            throw new IllegalParameterException("Node path is required for cmd RUN_SHELL callback");
        }

        onRunShellCallback(path, cmd, job);
        return;
    }

    if (cmd.getType() == CmdType.DELETE_SESSION) {
        LOGGER.trace("Session been deleted for job: %s", cmdQueueItem.getJobId());
        return;
    }

    LOGGER.warn("not found cmdType, cmdType: %s", cmd.getType().toString());
    throw new NotFoundException("not found cmdType");
}
项目:buabook-api-interface    文件:ApiOutboundRequest.java   
public ApiOutboundRequest(EBrokerCommands command, ERequestMethod requestMethod, String requestUrl) {
    if(command == null || requestMethod == null || Strings.isNullOrEmpty(requestUrl))
        throw new IllegalArgumentException("No null arguments permitted");

    this.command = command;
    this.requestMethod = requestMethod;
    this.requestUrl = requestUrl;

    this.clientRequests = new ArrayList<>();
}
项目:HCFCore    文件:LivesCheckDeathbanArgument.java   
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
    if (args.length < 2) {
        sender.sendMessage(ChatColor.RED + "Usage: " + getUsage(label));
        return true;
    }

    OfflinePlayer target = Bukkit.getOfflinePlayer(args[1]); // TODO: breaking

    if (!target.hasPlayedBefore() && !target.isOnline()) {
        sender.sendMessage(ChatColor.GOLD + "Player '" + ChatColor.WHITE + args[1] + ChatColor.GOLD + "' not found.");
        return true;
    }

    Deathban deathban = plugin.getUserManager().getUser(target.getUniqueId()).getDeathban();

    if (deathban == null || !deathban.isActive()) {
        sender.sendMessage(ChatColor.RED + target.getName() + " is not death-banned.");
        return true;
    }

    sender.sendMessage(ChatColor.DARK_AQUA + "Deathban cause of " + target.getName() + '.');
    sender.sendMessage(ChatColor.GRAY + " Time: " + DateTimeFormats.HR_MIN.format(deathban.getCreationMillis()));
    sender.sendMessage(ChatColor.GRAY + " Duration: " + DurationFormatUtils.formatDurationWords(deathban.getInitialDuration(), true, true));

    Location location = deathban.getDeathPoint();
    if (location != null) {
        sender.sendMessage(ChatColor.GRAY + " Location: (" + location.getBlockX() + ", " + location.getBlockY() + ", " + location.getBlockZ() + ") - " + location.getWorld().getName());
    }

    sender.sendMessage(ChatColor.GRAY + " Reason: [" + Strings.nullToEmpty(deathban.getReason()) + ChatColor.GREEN + "]");
    return true;
}
项目:firebase-admin-java    文件:FirebaseAuth.java   
/**
 * Similar to {@link #getUserByPhoneNumberAsync(String)}, but returns a {@link Task}.
 *
 * @param phoneNumber A user phone number string.
 * @return A {@link Task} which will complete successfully with a {@link UserRecord} instance.
 *     If an error occurs while retrieving user data or if the phone number does not
 *     correspond to a user, the task fails with a {@link FirebaseAuthException}.
 * @throws IllegalArgumentException If the phone number is null or empty.
 * @deprecated Use {@link #getUserByPhoneNumberAsync(String)}
 */
public Task<UserRecord> getUserByPhoneNumber(final String phoneNumber) {
  checkNotDestroyed();
  checkArgument(!Strings.isNullOrEmpty(phoneNumber), "phone number must not be null or empty");
  return call(new Callable<UserRecord>() {
    @Override
    public UserRecord call() throws Exception {
      return userManager.getUserByPhoneNumber(phoneNumber);
    }
  });
}