Example usage for org.springframework.util StringUtils hasLength

List of usage examples for org.springframework.util StringUtils hasLength

Introduction

In this page you can find the example usage for org.springframework.util StringUtils hasLength.

Prototype

public static boolean hasLength(@Nullable String str) 

Source Link

Document

Check that the given String is neither null nor of length 0.

Usage

From source file:com.vmware.thinapp.common.util.AfUtil.java

/**
 * Convert to a UNC path.// ww  w.  j  a va2s . com
 *
 * @param server a file share server hostname or ip.
 * @param share a share
 * @param path a path
 * @return a UNC formatted string.
 */
public static String toUNC(String server, String share, String path) {
    if (StringUtils.hasLength(path)) {
        return String.format("//%s/%s/%s", server, share, path).replace("/", "\\");
    }
    return String.format("//%s/%s", server, share).replace("/", "\\");
}

From source file:com.vmware.thinapp.common.util.AfUtil.java

/**
 * Extract filename for the HTTP response header.
 *
 * @param response a ClientHttpResponse.
 * @return a filename if found or null.//from   w w  w .  j  a v a  2s .c om
 */
public static final String getFilenameFromResponseHeader(ClientHttpResponse response) {
    String contentDisposition = response.getHeaders().getFirst(AfUtil.CONTENT_DISPOSITION);
    if (StringUtils.hasLength(contentDisposition)) {
        return AfUtil.getFilenameFromContentDisposition(contentDisposition);
    }
    return null;
}

From source file:com.vmware.thinapp.common.util.AfUtil.java

/**
 * Attempt to download the icon specified by the given URL.  If the resource at the URL
 * has a content type of image/*, the binary data for this resource will be downloaded.
 *
 * @param iconUrlStr URL of the image resource to access
 * @return the binary data and content type of the image resource at the given URL, null
 * if the URL is invalid, the resource does not have a content type starting with image/, or
 * on some other failure./* w  ww  .j  a v a2  s.c o m*/
 */
public static final @Nullable IconInfo getIconInfo(String iconUrlStr) {
    if (!StringUtils.hasLength(iconUrlStr)) {
        log.debug("No icon url exists.");
        return null;
    }
    URL iconUrl = null;
    try {
        // Need to encode any invalid characters before creating the URL object
        iconUrl = new URL(UriUtils.encodeHttpUrl(iconUrlStr, "UTF-8"));
    } catch (MalformedURLException ex) {
        log.debug("Malformed icon URL string: {}", iconUrlStr, ex);
        return null;
    } catch (UnsupportedEncodingException ex) {
        log.debug("Unable to encode icon URL string: {}", iconUrlStr, ex);
        return null;
    }

    // Open a connection with the given URL
    final URLConnection conn;
    final InputStream inputStream;
    try {
        conn = iconUrl.openConnection();
        inputStream = conn.getInputStream();
    } catch (IOException ex) {
        log.debug("Unable to open connection to URL: {}", iconUrlStr, ex);
        return null;
    }

    String contentType = conn.getContentType();
    int sizeBytes = conn.getContentLength();

    try {
        // Make sure the resource has an appropriate content type
        if (!conn.getContentType().startsWith("image/")) {
            log.debug("Resource at URL {} does not have a content type of image/*.", iconUrlStr);
            return null;
            // Make sure the resource is not too large
        } else if (sizeBytes > MAX_ICON_SIZE_BYTES) {
            log.debug("Image resource at URL {} is too large: {}", iconUrlStr, sizeBytes);
            return null;
        } else {
            // Convert the resource to a byte array
            byte[] iconBytes = ByteStreams.toByteArray(new InputSupplier<InputStream>() {
                @Override
                public InputStream getInput() throws IOException {
                    return inputStream;
                }
            });
            return new IconInfo(iconBytes, contentType);
        }
    } catch (IOException e) {
        log.debug("Error reading resource data.", e);
        return null;
    } finally {
        Closeables.closeQuietly(inputStream);
    }
}

From source file:com.wavemaker.runtime.server.ControllerBase.java

@Override
public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) {

    if (request == null) {
        throw new WMRuntimeException(MessageResource.SERVER_NOREQUEST);
    } else if (response == null) {
        throw new WMRuntimeException(MessageResource.SERVER_NORESPONSE);
    }/*from www.j  a  v a2  s .co m*/

    ModelAndView ret;
    try {
        this.runtimeAccess.setStartTime(System.currentTimeMillis());
        // add logging
        StringBuilder logEntry = new StringBuilder();
        HttpSession session = request.getSession(false);
        if (session != null) {
            logEntry.append("session " + session.getId() + ", ");
        }
        logEntry.append("thread " + Thread.currentThread().getId());
        NDC.push(logEntry.toString());

        // default responses to the DEFAULT_ENCODING
        response.setCharacterEncoding(ServerConstants.DEFAULT_ENCODING);

        getServletEventNotifier().executeStartRequest();
        initializeRuntime(request, response);

        // execute the request
        ret = executeRequest(request, response);

        getServletEventNotifier().executeEndRequest();
    } catch (Throwable t) {
        this.logger.error(t.getMessage(), t);
        String message = t.getMessage();
        if (!StringUtils.hasLength(message)) {
            message = t.toString();
        }
        if (this.serviceResponse != null && !this.serviceResponse.isPollingRequest()
                && this.serviceResponse.getConnectionTimeout() > 0
                && System.currentTimeMillis()
                        - this.runtimeAccess.getStartTime() > (this.serviceResponse.getConnectionTimeout() - 3)
                                * 1000) {
            this.serviceResponse.addError(t);
        }
        return handleError(message, t);
    } finally {
        RuntimeAccess.setRuntimeBean(null);
        NDC.pop();
        NDC.remove();
    }

    return ret;
}

From source file:com.wavemaker.studio.StudioService.java

@ExposeToClient
public FileUploadResponse uploadJar(MultipartFile file) {
    FileUploadResponse ret = new FileUploadResponse();
    try {/*from   w  w  w .  j a  va  2s  .co  m*/
        String filename = file.getOriginalFilename();
        String filenameExtension = StringUtils.getFilenameExtension(filename);
        if (!StringUtils.hasLength(filenameExtension)) {
            throw new IOException("Please upload a jar file");
        }
        if (!"jar".equals(filenameExtension)) {
            throw new IOException("Please upload a jar file, not a " + filenameExtension + " file");
        }
        Folder destinationFolder = this.fileSystem.getStudioWebAppRootFolder().getFolder("WEB-INF/lib");
        File destinationFile = destinationFolder.getFile(filename);
        destinationFile.getContent().write(file.getInputStream());
        ret.setPath(destinationFile.getName());

        // Copy jar to common/lib in WaveMaker Home
        Folder commonLib = fileSystem.getWaveMakerHomeFolder().getFolder(CommonConstants.COMMON_LIB);
        commonLib.createIfMissing();
        File destinationJar = commonLib.getFile(filename);
        destinationJar.getContent().write(file.getInputStream());

        // Copy jar to project's lib
        com.wavemaker.tools.io.ResourceFilter included = FilterOn.antPattern("*.jar");
        commonLib.find().include(included).files()
                .copyTo(this.projectManager.getCurrentProject().getRootFolder().getFolder("lib"));
    } catch (IOException e) {
        ret.setError(e.getMessage());
    }
    return ret;
}

From source file:com.wavemaker.tools.cloudfoundry.spinup.authentication.SharedSecretPropagation.java

/**
 * Get the shared secret for the currently running application. This method assumes that some other process has
 * {@link #sendTo(CloudFoundryClient, SharedSecret, CloudApplication) sent} the {@link SharedSecret} to the running
 * application./* w  ww  .  j ava2  s  . c  om*/
 * 
 * @param required
 * 
 * @return the shared secret
 * @throw IllegalStateException if the secret cannot be obtained
 */
public SharedSecret getForSelf(boolean required) throws IllegalStateException {
    try {
        String secret = getEnv(ENV_KEY);
        if (!StringUtils.hasLength(secret) && !required) {
            return null;
        }
        Assert.state(StringUtils.hasLength(secret), "No shared secret has been propagated");
        return SharedSecret.fromBytes(Hex.decodeHex(secret.toCharArray()));
    } catch (DecoderException e) {
        throw new IllegalStateException("Unable to decode shared secret key", e);
    }
}

From source file:com.wavemaker.tools.cloudfoundry.spinup.DefaultSpinupService.java

/**
 * @return The actual controller URL to use.
 *///from ww w . ja va  2s . c  o  m
private String getControllerUrl() {
    if (StringUtils.hasLength(this.controllerUrl)) {
        return this.controllerUrl;
    }
    String systemEnv = System.getenv(CLOUD_CONTROLLER_VARIABLE_NAME);
    if (StringUtils.hasLength(systemEnv)) {
        return systemEnv;
    }
    systemEnv = System.getProperty(CLOUD_CONTROLLER_VARIABLE_NAME);
    if (StringUtils.hasLength(systemEnv)) {
        return systemEnv;
    }
    return "http://api.cloudfoundry.com";
}

From source file:com.wavemaker.tools.compiler.ProjectCompiler.java

private Iterable<java.io.File> getStandardClassPath() {
    String catalinaBase = System.getProperty("catalina.base");
    if (!StringUtils.hasLength(catalinaBase)) {
        this.logger.warn("Unable to locate running tomcat instance, servlet-api jar will not be available");
        return null;
    }//  w  w  w  . j av  a2 s  .c  om
    return Collections.singleton(new java.io.File(catalinaBase + "/lib/servlet-api.jar"));
}

From source file:com.wavemaker.tools.deployment.cloudfoundry.CloudFoundryDeploymentTarget.java

private AuthenticationToken getAuthenticationToken() {
    RuntimeAccess runtimeAccess = RuntimeAccess.getInstance();
    if (runtimeAccess == null) {
        return null;
    }// ww  w  .  j  a v a 2 s  .co m
    Cookie cookie = WebUtils.getCookie(runtimeAccess.getRequest(), "wavemaker_authentication_token");
    if (cookie == null || !StringUtils.hasLength(cookie.getValue())) {
        return null;
    }
    SharedSecret sharedSecret = this.propagation.getForSelf(false);
    if (sharedSecret == null) {
        return null;
    }
    AuthenticationToken authenticationToken = sharedSecret.decrypt(TransportToken.decode(cookie.getValue()));
    return authenticationToken;
}

From source file:com.wavemaker.tools.project.AbstractDeploymentManager.java

public static Deployments readDeployments(Project project, StudioFileSystem fileSystem) {
    com.wavemaker.tools.io.File file = fileSystem.getCommonFolder().getFile(DEPLOYMENTS_FILE);
    String content = file.exists() ? file.getContent().asString() : "";
    if (!StringUtils.hasLength(content)) {
        return new Deployments();
    }/*from  www .j a v a 2  s . c  o  m*/
    JSON result = JSONUnmarshaller.unmarshal(content);
    Assert.isTrue(result instanceof JSONObject, file.toString() + " is in an unexpected format.");
    return (Deployments) JSONUtils.toBean((JSONObject) result, Deployments.class);
}