Java Code Examples for spark.utils.StringUtils

The following examples show how to use spark.utils.StringUtils. These examples are extracted from open source projects. 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 Project: gocd   Source File: InternalCommandSnippetsControllerV1.java    License: Apache License 2.0 6 votes vote down vote up
public String index(Request request, Response response) throws IOException {
    String prefix = request.queryParams(PREFIX_PARAM);
    if (StringUtils.isEmpty(prefix)) {
        throw HaltApiResponses.haltBecauseRequiredParamMissing(PREFIX_PARAM);
    }

    List<CommandSnippet> commandSnippets = commandRepositoryService.lookupCommand(prefix);

    String etag = etagFor(commandSnippets);

    if (fresh(request, etag)) {
        return notModified(response);
    }

    setEtagHeader(response, etag);
    return writerForTopLevelObject(request, response, outputWriter -> CommandSnippetsRepresenter.toJSON(outputWriter, commandSnippets, prefix));
}
 
Example 2
Source Project: butterfly   Source File: BaseRequestHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Takes the raw, unencrypted and decompressed bytes, transforms them as necessary, and sends
 * them to the client.
 * @param respBytes The bytes to send.
 * @param request The original request.
 * @param response The response object we can use to send the data.
 * @return A response object for Spark
 */
protected Object sendBytesToClient(byte[] respBytes, final Request request, final Response response) {
    response.header("Connection", "keep-alive");

    // convert them to binary XML
    if (!XmlUtils.isBinaryXML(respBytes)) {
        respBytes = PublicKt.kbinEncode(new String(respBytes), "UTF-8");
    }

    response.header(COMPRESSION_HEADER, "none");

    // encrypt if needed
    final String encryptionKey = request.headers(CRYPT_KEY_HEADER);

    if (!StringUtils.isBlank(encryptionKey)) {
        respBytes = Rc4.encrypt(respBytes, encryptionKey);
        response.header(CRYPT_KEY_HEADER, encryptionKey);
    }

    // send to the client
    try {
        final HttpServletResponse rawResponse = response.raw();
        response.type(MediaType.OCTET_STREAM.toString());

        rawResponse.getOutputStream().write(respBytes);
        rawResponse.getOutputStream().flush();
        rawResponse.getOutputStream().close();

        LOG.info("Response sent: " + request.queryParams("model") + " (" +
                request.queryParams("module") + "." + request.queryParams("method") + ")");

        return 200;
    } catch (IOException e) {
        e.printStackTrace();
        return 500;
    }
}
 
Example 3
Source Project: minitwit   Source File: User.java    License: MIT License 5 votes vote down vote up
public String validate() {
	String error = null;
	
	if(StringUtils.isEmpty(username)) {
		error = "You have to enter a username";
	} else if(!EMAIL_ADDRESS_REGEX.matcher(email).matches()) {
		error = "You have to enter a valid email address";
	} else if(StringUtils.isEmpty(password)) {
		error = "You have to enter a password";
	} else if(!password.equals(password2)) {
		error = "The two passwords do not match";
	}
	
	return error;
}
 
Example 4
Source Project: ha-bridge   Source File: User.java    License: Apache License 2.0 5 votes vote down vote up
public String validate() {
	String error = null;
	
	if(StringUtils.isEmpty(username)) {
		error = "You have to enter a username";
	} else if(StringUtils.isEmpty(password)) {
		error = "You have to enter a password";
	} else if(!password.equals(password2)) {
		error = "The two passwords do not match";
	}
	
	return error;
}
 
Example 5
Source Project: james-project   Source File: SieveScriptRoutes.java    License: Apache License 2.0 5 votes vote down vote up
private Username extractUser(Request request) throws UsersRepositoryException {
    Username userName = Optional.ofNullable(request.params(USER_NAME))
        .map(String::trim)
        .filter(StringUtils::isNotEmpty)
        .map(Username::of)
        .orElseThrow(() -> throw400withInvalidArgument("Invalid username"));

    if (!usersRepository.contains(userName)) {
        throw404("User not found");
    }
    return userName;
}
 
Example 6
Source Project: james-project   Source File: SieveScriptRoutes.java    License: Apache License 2.0 5 votes vote down vote up
private ScriptName extractScriptName(Request request) {
    return Optional.ofNullable(request.params(SCRIPT_NAME))
        .map(String::trim)
        .filter(StringUtils::isNotEmpty)
        .map(ScriptName::new)
        .orElseThrow(() -> throw400withInvalidArgument("Invalid Sieve script name"));
}
 
Example 7
Source Project: gocd   Source File: ConfigRepoOperationsControllerV1.java    License: Apache License 2.0 5 votes vote down vote up
private ConfigRepoPlugin pluginFromRequest(Request req) {
    String pluginId = req.queryParams("pluginId");
    if (StringUtils.isBlank(pluginId)) {
        throw HaltApiResponses.haltBecauseRequiredParamMissing("pluginId");
    }
    return (ConfigRepoPlugin) pluginService.partialConfigProviderFor(pluginId);
}
 
Example 8
Source Project: gocd   Source File: UsageStatisticsControllerV3.java    License: Apache License 2.0 5 votes vote down vote up
private boolean verifySignatureAndPublicKey(String signature, String subordinatePublicKey, HttpLocalizedOperationResult result) throws Exception {
    if (StringUtils.isEmpty(signature)) {
        result.unprocessableEntity(String.format("Please provide '%s' field.", SIGNATURE_KEY));
        return false;
    }

    if (StringUtils.isEmpty(subordinatePublicKey)) {
        result.unprocessableEntity(String.format("Please provide '%s' field.", SUBORDINATE_PUBLIC_KEY));
        return false;
    }

    String masterPublicKey = FileUtils.readFileToString(new File(systemEnvironment.getUpdateServerPublicKeyPath()), "utf8");

    boolean isVerified;
    try {
        isVerified = EncryptionHelper.verifyRSASignature(subordinatePublicKey, signature, masterPublicKey);
    } catch (Exception e) {
        isVerified = false;
    }

    if (!isVerified) {
        result.unprocessableEntity(String.format("Invalid '%s' or '%s' provided.", SIGNATURE_KEY, SUBORDINATE_PUBLIC_KEY));
        return false;
    }

    return true;
}
 
Example 9
Source Project: butterfly   Source File: ButterflyHttpServer.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Validates incoming requests for basic sanity checks, and returns the request
 * as a plaintext XML document.
 * @param request The incoming request.
 * @return An <code>Element</code> representing the root of the request document
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 */
private Element validateAndUnpackRequest(Request request) {
    final String requestUriModel = request.queryParams("model");
    final String requestUriModule = request.queryParams("module");
    final String requestUriMethod = request.queryParams("method");

    LOG.info("Request received: " + requestUriModel + " (" + requestUriModule + "." + requestUriMethod + ")");

    // validate that the PCBID exists in the database
    final String encryptionKey = request.headers(CRYPT_KEY_HEADER);
    final String compressionScheme = request.headers(COMPRESSION_HEADER);
    byte[] reqBody = request.bodyAsBytes();

    // decrypt the request if it's encrypted
    if (!StringUtils.isBlank(encryptionKey)) {
        reqBody = Rc4.decrypt(reqBody, encryptionKey);
    }

    // decompress the request if it's compressed
    if (!StringUtils.isBlank(compressionScheme) &&
            compressionScheme.equals(LZ77_COMPRESSION)) {
        reqBody = Lz77.decompress(reqBody);
    }

    // convert the body to plaintext XML if it's binary XML
    Element rootNode = null;

    if (XmlUtils.isBinaryXML(reqBody)) {
        rootNode = XmlUtils.stringToXmlFile(PublicKt.kbinDecodeToString(reqBody));
    } else {
        rootNode = XmlUtils.byteArrayToXmlFile(reqBody);
    }

    // read the request body into an XML document
    if (rootNode == null ||
            !rootNode.getNodeName().equals("call")) {
        throw new InvalidRequestException();
    }

    final Element moduleNode = (Element) rootNode.getFirstChild();
    final String requestBodyModel = rootNode.getAttribute("model");
    final String requestBodyPcbId = rootNode.getAttribute("srcid");
    final String requestBodyModule = moduleNode.getNodeName();
    final String requestBodyMethod = moduleNode.getAttribute("method");

    // check if the PCB exists and is unbanned in the database
    Machine machine = this.machineDao.findByPcbId(requestBodyPcbId);

    if (machine == null) {
        // create a machine for auditing purposes, and ban them
        final LocalDateTime now = LocalDateTime.now();
        final ButterflyUser newUser = new ButterflyUser("0000", now, now, 10000);
        userDao.create(newUser);

        machine = new Machine(newUser, requestBodyPcbId, LocalDateTime.now(), false, 0);
        machineDao.create(machine);

        throw new InvalidPcbIdException();
    } else if (!machine.isEnabled()) {
        throw new InvalidPcbIdException();
    }

    // validate that the request URI matches the request body
    if (StringUtils.isBlank(requestBodyModel) ||
            StringUtils.isBlank(requestBodyModule) ||
            StringUtils.isBlank(requestBodyMethod) ||
            !requestBodyModel.equals(requestUriModel) ||
            !requestBodyModule.equals(requestUriModule) ||
            !requestBodyMethod.equals(requestUriMethod)) {
        throw new MismatchedRequestUriException();
    }

    // set the model, pcbid, module, and method as request "attributes" so they can be
    // used by the request handlers if needed
    request.attribute("model", requestBodyModel);
    request.attribute("pcbid", requestBodyPcbId);
    request.attribute("module", requestBodyModule);
    request.attribute("method", requestBodyMethod);

    // return the node corresponding to the actual call
    return moduleNode;
}