Java Code Examples for org.apache.commons.lang3.StringUtils.trimToEmpty()

The following are Jave code examples for showing how to use trimToEmpty() of the org.apache.commons.lang3.StringUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: RuuviCollector   File: Config.java   View Source Code Vote up 6 votes
private static void readTagNames() {
    try {
        File jarLocation = new File(Config.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile();
        File[] configFiles = jarLocation.listFiles(f -> f.isFile() && f.getName().equals("ruuvi-names.properties"));
        if (configFiles == null || configFiles.length == 0) {
            // look for config files in the parent directory if none found in the current directory, this is useful during development when
            // RuuviCollector can be run from maven target directory directly while the config file sits in the project root
            configFiles = jarLocation.getParentFile().listFiles(f -> f.isFile() && f.getName().equals("ruuvi-names.properties"));
        }
        if (configFiles != null && configFiles.length > 0) {
            LOG.debug("Tag names: " + configFiles[0]);
            Properties props = new Properties();
            props.load(new FileInputStream(configFiles[0]));
            Enumeration<?> e = props.propertyNames();
            while (e.hasMoreElements()) {
                String key = StringUtils.trimToEmpty((String) e.nextElement()).toUpperCase();
                String value = StringUtils.trimToEmpty(props.getProperty(key));
                if (key.length() == 12 && value.length() > 0) {
                    TAG_NAMES.put(key, value);
                }
            }
        }
    } catch (URISyntaxException | IOException ex) {
        LOG.warn("Failed to read tag names", ex);
    }
}
 
Example 2
Project: fat-lining   File: ValidationUtils.java   View Source Code Vote up 6 votes
/**
 * Validate passwords input
 * <ul>
 *  <li>password is not empty</li>
 *  <li>password has appropriate length</li>
 *  <li>password and repeated password match</li>
 * </ul>
 * @param password to validate
 * @param repeatedPassword to validate
 * @param errors resulting to validation
 */
public void validatePasswords(String password, String repeatedPassword, Errors errors) {
	String cleanPassword = StringUtils.trimToEmpty(password);
	if (StringUtils.isBlank(cleanPassword)) {
		errors.rejectValue("password", "validation.error.password.blank");
	} else if (StringUtils.length(cleanPassword) < config.getPasswordLength()) {
		errors.rejectValue("password", "validation.error.password.tooShort", new Object[]{config.getPasswordLength()}, StringUtils.EMPTY);
	} else {
		String cleanRepeatedPassword = StringUtils.trimToEmpty(repeatedPassword);
		if (!StringUtils.equals(cleanPassword, cleanRepeatedPassword)) {
			errors.rejectValue("repeatedPassword", "validation.error.password.noMatch");
		}
	}
	
}
 
Example 3
Project: plugin-bt-jira   File: JiraBaseResource.java   View Source Code Vote up 6 votes
/**
 * Prepare an authenticated connection to JIRA
 */
protected boolean authenticateAdmin(final Map<String, String> parameters, final CurlProcessor processor) {
	final String user = parameters.get(PARAMETER_ADMIN_USER);
	final String password = StringUtils.trimToEmpty(parameters.get(PARAMETER_ADMIN_PASSWORD));
	final String baseUrl = parameters.get(PARAMETER_URL);
	final String url = StringUtils.appendIfMissing(baseUrl, "/") + "login.jsp";
	final List<CurlRequest> requests = new ArrayList<>();
	requests.add(new CurlRequest(HttpMethod.GET, url, null));
	requests.add(new CurlRequest(HttpMethod.POST, url,
			"os_username=" + user + "&os_password=" + password + "&os_destination=&atl_token=&login=Connexion",
			JiraCurlProcessor.LOGIN_CALLBACK, "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));

	// Sudoing is only required for JIRA 4+
	if ("4".compareTo(getVersion(parameters)) <= 0) {
		requests.add(
				new CurlRequest(HttpMethod.POST, StringUtils.appendIfMissing(baseUrl, "/") + "secure/admin/WebSudoAuthenticate.jspa",
						"webSudoIsPost=false&os_cookie=true&authenticate=Confirm&webSudoPassword=" + password,
						JiraCurlProcessor.SUDO_CALLBACK, "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
	}
	return processor.process(requests);
}
 
Example 4
Project: yadaframework   File: AuditFilter.java   View Source Code Vote up 5 votes
/**
 * Forwards the request to the next filter in the chain and delegates down to the subclasses to perform the actual
 * request logging both before and after the request is processed.
 *
 * @see #beforeRequest
 * @see #afterRequest
 */
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
	if (resourceUrlStart==null) {
		resourceUrlStart = request.getContextPath() + YadaWebConfig.getResourceFolder() + "-"; // /site/res-
	}
	boolean isFirstRequest = !isAsyncDispatch(request);
	long startTime = -1;
	String sessionId = "";
	String username = "";
	// Questo codice per il calcolo dell'IP è stato messo in YadaWebUtil ma accedere quello da qui non viene facile, per cui duplico qui
	String remoteAddr = request.getRemoteAddr();
	String forwardedFor = request.getHeader("X-Forwarded-For");
	String remoteIp = "?";
	if (!StringUtils.isBlank(remoteAddr)) {
		remoteIp = remoteAddr;
	}
	if (!StringUtils.isBlank(forwardedFor)) {
		remoteIp = "[for " + forwardedFor + "]";
	}
	//
	String requestUri = request.getRequestURI();
	HttpSession session = request.getSession(false);
	SecurityContext securityContext = null;
	if (session!=null) {
		sessionId = StringUtils.trimToEmpty(session.getId());
		securityContext = ((SecurityContext)session.getAttribute("SPRING_SECURITY_CONTEXT"));
	}
	if (sessionId.length()==0) {
		sessionId = "req-"+Integer.toString(request.hashCode());
	}
	if (securityContext!=null) {
		try {
			username = securityContext.getAuthentication().getName();
		} catch (Exception e) {
			log.debug("No username in securityContext");
		}
	}
	MDC.put(MDC_SESSION, sessionId); // Session viene messo sull'MDC. Usarlo con %X{session} nel pattern
	MDC.put(MDC_USERNAME, username); // username viene messo sull'MDC. Usarlo con %X{username} nel pattern		
	MDC.put(MDC_REMOTEIP, remoteIp); // remoteIp viene messo sull'MDC. Usarlo con %X{remoteIp} nel pattern		

	if (isFirstRequest) {
		beforeRequest(request);
		startTime = System.currentTimeMillis();
	}
	try {
		filterChain.doFilter(request, response);
		int status = response.getStatus();
		if (!skipDuration(requestUri) && !isAsyncStarted(request)) {
			if (startTime>-1) {
				long timetaken = System.currentTimeMillis()-startTime;
				log.info("{}: {} ms (HTTP {})", requestUri, timetaken, status);
			}
		} else if (status>399) {
			log.error("{} HTTP {}", requestUri, status);
		}
	} finally {
		MDC.remove(MDC_USERNAME);
		MDC.remove(MDC_SESSION);
		MDC.remove(MDC_REMOTEIP);
	}
}
 
Example 5
Project: plugin-km-confluence   File: ConfluencePluginResource.java   View Source Code Vote up 5 votes
/**
 * Prepare an authenticated connection to Confluence
 */
protected void authenticate(final Map<String, String> parameters, final CurlProcessor processor) {
	final String user = parameters.get(PARAMETER_USER);
	final String password = StringUtils.trimToEmpty(parameters.get(PARAMETER_PASSWORD));
	final String url = StringUtils.appendIfMissing(parameters.get(PARAMETER_URL), "/") + "dologin.action";
	final List<CurlRequest> requests = new ArrayList<>();
	requests.add(new CurlRequest(HttpMethod.GET, url, null));
	requests.add(new CurlRequest(HttpMethod.POST, url,
			"os_username=" + user + "&os_password=" + password + "&os_destination=&atl_token=&login=Connexion",
			ConfluenceCurlProcessor.LOGIN_CALLBACK, "Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"));
	if (!processor.process(requests)) {
		throw new ValidationJsonException(PARAMETER_URL, "confluence-login", parameters.get(PARAMETER_USER));
	}
}
 
Example 6
Project: plugin-vm-vcloud   File: VCloudPluginResource.java   View Source Code Vote up 5 votes
/**
 * Prepare an authenticated connection to vCloud. The given processor would
 * be updated with the security token.
 */
protected void authenticate(final Map<String, String> parameters, final VCloudCurlProcessor processor) {
	final String user = parameters.get(PARAMETER_USER);
	final String password = StringUtils.trimToEmpty(parameters.get(PARAMETER_PASSWORD));
	final String organization = StringUtils.trimToEmpty(parameters.get(PARAMETER_ORGANIZATION));
	final String url = StringUtils.appendIfMissing(parameters.get(PARAMETER_API), "/") + "sessions";

	// Encode the authentication '[email protected]:password'
	final String authentication = Base64
			.encodeBase64String((user + "@" + organization + ":" + password).getBytes(StandardCharsets.UTF_8));

	// Authentication request using cache
	processor.setToken(authenticate(url, authentication, processor));
}
 
Example 7
Project: NGB-master   File: CytobandReader.java   View Source Code Vote up 4 votes
private String getText(final String[] columns, final Cols col) {
    return StringUtils.trimToEmpty(columns[col.index()]);
}
 
Example 8
Project: sipsoup   File: XpathStateMachine.java   View Source Code Vote up 4 votes
@Override
public void parse(XpathStateMachine stateMachine) throws XpathSyntaxErrorException {
    // 轴解析
    if (!stateMachine.tokenQueue.hasAxis()) {
        stateMachine.state = TAG;
        return;
    }

    String axisFunctionStr = stateMachine.tokenQueue.consumeTo("::");
    stateMachine.tokenQueue.consume("::");
    TokenQueue functionTokenQueue = new TokenQueue(axisFunctionStr);
    String functionName = functionTokenQueue.consumeCssIdentifier().trim();
    functionTokenQueue.consumeWhitespace();

    AxisFunction axisFunction = FunctionEnv.getAxisFunction(functionName);
    if (axisFunction == null) {
        throw new NoSuchAxisException(stateMachine.tokenQueue.nowPosition(),
                "not such axis " + functionName);
    }
    stateMachine.xpathChain.getXpathNodeList().getLast().setAxis(axisFunction);

    if (functionTokenQueue.isEmpty()) {
        stateMachine.state = TAG;
        return;
    }

    // 带有参数的轴函数
    if (!functionTokenQueue.matches("(")) {// 必须以括号开头
        throw new XpathSyntaxErrorException(stateMachine.tokenQueue.nowPosition(),
                "expression is not a function:\"" + axisFunctionStr + "\"");
    }
    String paramList = StringUtils.trimToEmpty(functionTokenQueue.chompBalanced('(', ')'));
    functionTokenQueue.consumeWhitespace();
    if (!functionTokenQueue.isEmpty()) {
        throw new XpathSyntaxErrorException(stateMachine.tokenQueue.nowPosition(),
                "expression is not a function: \"" + axisFunctionStr + "\" can not recognize token:"
                        + functionTokenQueue.remainder());
    }

    // 解析参数列表
    TokenQueue paramTokenQueue = new TokenQueue(paramList);
    LinkedList<String> params = Lists.newLinkedList();
    while (!paramTokenQueue.isEmpty()) {
        paramTokenQueue.consumeWhitespace();
        if (!paramTokenQueue.isEmpty() && paramTokenQueue.peek() == ',') {
            paramTokenQueue.advance();
            paramTokenQueue.consumeWhitespace();
        }
        String param;
        if (paramTokenQueue.matches("\"")) {
            param = paramTokenQueue.chompBalanced('\"', '\"');
            if (paramTokenQueue.peek() == ',') {
                paramTokenQueue.consume();
            }
        } else if (paramTokenQueue.matches("\'")) {
            param = paramTokenQueue.chompBalanced('\'', '\'');
            if (paramTokenQueue.peek() == ',') {
                paramTokenQueue.consume();
            }
        } else {
            param = paramTokenQueue.consumeTo(",");
            if (StringUtils.isEmpty(param)) {
                continue;
            }
        }
        params.add(TokenQueue.unescape(StringUtils.trimToEmpty(param)));
    }
    stateMachine.xpathChain.getXpathNodeList().getLast().setAxisParams(params);
    stateMachine.state = TAG;
}
 
Example 9
Project: sipsoup   File: XpathStateMachine.java   View Source Code Vote up 4 votes
@Override
public void parse(XpathStateMachine stateMachine) throws XpathSyntaxErrorException {
    stateMachine.tokenQueue.consumeWhitespace();
    if (stateMachine.tokenQueue.peek() == '*') {
        stateMachine.tokenQueue.advance();
        stateMachine.tokenQueue.consumeWhitespace();
        stateMachine.xpathChain.getXpathNodeList().getLast()
                .setSelectFunction(FunctionEnv.getSelectFunction("tag"));
        stateMachine.xpathChain.getXpathNodeList().getLast().setSelectParams(Lists.newArrayList("*"));
        stateMachine.state = PREDICATE;
        return;
    }

    if (stateMachine.tokenQueue.matchesFunction()) {// 遇到主干抽取函数,后面不能有谓语
        String function = stateMachine.tokenQueue.consumeFunction();
        TokenQueue functionTokenQueue = new TokenQueue(function);
        String functionName = functionTokenQueue.consumeTo("(");
        LinkedList<String> params = Lists.newLinkedList();
        TokenQueue paramTokenQueue = new TokenQueue(StringUtils.trimToEmpty(functionTokenQueue.chompBalanced('(', ')')));
        while ((paramTokenQueue.consumeWhitespace() && !paramTokenQueue.consumeWhitespace())
                || !paramTokenQueue.isEmpty()) {
            String param;
            if (paramTokenQueue.matches("\"")) {
                param = paramTokenQueue.chompBalanced('\"', '\"');
                if (paramTokenQueue.peek() == ',') {
                    paramTokenQueue.advance();
                }
            } else if (paramTokenQueue.matches("\'")) {
                param = paramTokenQueue.chompBalanced('\'', '\'');
                if (paramTokenQueue.peek() == ',') {
                    paramTokenQueue.advance();
                }
            } else {
                param = paramTokenQueue.consumeTo(",");
            }
            params.add(TokenQueue.unescape(StringUtils.trimToEmpty(param)));
        }
        stateMachine.xpathChain.getXpathNodeList().getLast()
                .setSelectFunction(FunctionEnv.getSelectFunction(functionName));
        stateMachine.xpathChain.getXpathNodeList().getLast().setSelectParams(params);
        stateMachine.state = PREDICATE;// TODO 后面是否支持谓语,如果支持的话,谓语数据结构需要修改
        return;
    }
    if (stateMachine.tokenQueue.matches("@")) {// 遇到属性抽取动作
        stateMachine.tokenQueue.advance();
        stateMachine.tokenQueue.consumeWhitespace();
        stateMachine.xpathChain.getXpathNodeList().getLast()
                .setSelectFunction(FunctionEnv.getSelectFunction("@"));
        if (stateMachine.tokenQueue.peek() == '*') {
            stateMachine.tokenQueue.advance();
            stateMachine.xpathChain.getXpathNodeList().getLast().setSelectParams(Lists.newArrayList("*"));
        } else {
            String attributeKey = stateMachine.tokenQueue.consumeAttributeKey();
            stateMachine.xpathChain.getXpathNodeList().getLast()
                    .setSelectParams(Lists.newArrayList(attributeKey));
        }
        stateMachine.state = PREDICATE;
        stateMachine.tokenQueue.consumeWhitespace();
        return;
    }

    String tagName = stateMachine.tokenQueue.consumeTagName();
    if (StringUtils.isEmpty(tagName)) {
        throw new XpathSyntaxErrorException(stateMachine.tokenQueue.nowPosition(),
                "can not recognize token,expected start with a tagName,actually is:"
                        + stateMachine.tokenQueue.remainder());
    }
    stateMachine.xpathChain.getXpathNodeList().getLast()
            .setSelectFunction(FunctionEnv.getSelectFunction("tag"));
    stateMachine.xpathChain.getXpathNodeList().getLast().setSelectParams(Lists.newArrayList(tagName));
    stateMachine.state = PREDICATE;
}
 
Example 10
Project: cas-5.1.0   File: OidcAuthenticationContextWebflowEventEventResolver.java   View Source Code Vote up 4 votes
@Override
public Set<Event> resolveInternal(final RequestContext context) {
    final RegisteredService service = resolveRegisteredServiceInRequestContext(context);
    final Authentication authentication = WebUtils.getAuthentication(context);
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);

    if (service == null || authentication == null) {
        LOGGER.debug("No service or authentication is available to determine event for principal");
        return null;
    }

    String acr = request.getParameter(OAuth20Constants.ACR_VALUES);
    if (StringUtils.isBlank(acr)) {
        final URIBuilder builderContext = new URIBuilder(StringUtils.trimToEmpty(context.getFlowExecutionUrl()));
        final Optional<URIBuilder.BasicNameValuePair> parameter = builderContext.getQueryParams()
                .stream().filter(p -> p.getName().equals(OAuth20Constants.ACR_VALUES))
                .findFirst();
        if (parameter.isPresent()) {
            acr = parameter.get().getValue();
        }
    }
    if (StringUtils.isBlank(acr)) {
        LOGGER.debug("No ACR provided in the authentication request");
        return null;
    }
    final Set<String> values = org.springframework.util.StringUtils.commaDelimitedListToSet(acr);
    if (values.isEmpty()) {
        LOGGER.debug("No ACR provided in the authentication request");
        return null;
    }

    final Map<String, MultifactorAuthenticationProvider> providerMap =
            WebUtils.getAvailableMultifactorAuthenticationProviders(this.applicationContext);
    if (providerMap == null || providerMap.isEmpty()) {
        LOGGER.error("No multifactor authentication providers are available in the application context to handle [{}]", values);
        throw new AuthenticationException();
    }

    final Collection<MultifactorAuthenticationProvider> flattenedProviders = flattenProviders(providerMap.values());
    final Optional<MultifactorAuthenticationProvider> provider = flattenedProviders
            .stream()
            .filter(v -> values.contains(v.getId())).findAny();

    if (provider.isPresent()) {
        return Collections.singleton(new Event(this, provider.get().getId()));
    }
    LOGGER.warn("The requested authentication class [{}] cannot be satisfied by any of the MFA providers available", values);
    throw new AuthenticationException();
}
 
Example 11
Project: HL7Receiver   File: CodeCacheKey.java   View Source Code Vote up 4 votes
public CodeCacheKey(String context, String code, String codeSystem, String term) {
    this.context = StringUtils.trimToEmpty(context);
    this.code = StringUtils.trimToEmpty(code);
    this.codeSystem = StringUtils.trimToEmpty(codeSystem);
    this.term = StringUtils.trimToEmpty(term);
}
 
Example 12
Project: vscrawler   File: TrimToEmpty.java   View Source Code Vote up 4 votes
@Override
protected String handleSingleStr(String input) {
    return StringUtils.trimToEmpty(input);
}
 
Example 13
Project: cryptotrader   File: BitflyerContext.java   View Source Code Vote up 4 votes
@Override
public ZonedDateTime getExpiry(Key key) {

    String code = StringUtils.trimToEmpty(convertProductAlias(key));

    if (!EXPIRY_PATTERN.matcher(code).matches()) {
        return null;
    }

    ZonedDateTime expiry;

    try {

        String value = code.substring(6) + EXPIRY_TIME;

        Date date = EXPIRY_FORMAT.get().parse(value);

        ZoneId zone = ZoneId.of(EXPIRY_FORMAT.get().getTimeZone().getID());

        expiry = ZonedDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), zone);

    } catch (ParseException e) {

        expiry = null;

    }

    return expiry;

}
 
Example 14
Project: fat-lining   File: ValidationUtils.java   View Source Code Vote up 3 votes
/**
 * Validate current password
 * <ul>
 * 	<li>current password and entered password have to match</li>
 * </ul>
 * @param currentPassword
 * @param errors
 */
public void validateCurrentPassword(String currentPassword, Errors errors) {
	String cleanCurrentPassword = StringUtils.trimToEmpty(currentPassword);
	AppUser currentUser = manager.getCurrentUser();
	if (!encoder.matches(cleanCurrentPassword, currentUser.getHash())) {
		errors.rejectValue("currentPassword", "validation.error.password.wrongPassword");
	}
}
 
Example 15
Project: cryptotrader   File: BitmexContext.java   View Source Code Vote up 3 votes
@VisibleForTesting
String computeHash(String secret, String method, String path, String nonce, String data) throws IOException {

    try {

        Mac mac = Mac.getInstance("HmacSHA256");

        mac.init(new SecretKeySpec(secret.getBytes(), "HmacSHA256"));

        String raw = method + path + nonce + StringUtils.trimToEmpty(data);

        byte[] hash = mac.doFinal(raw.getBytes());

        StringBuilder sb = new StringBuilder(hash.length);

        for (byte b : hash) {
            sb.append(String.format("%02x", b & 0xff));
        }

        return sb.toString();

    } catch (GeneralSecurityException e) {

        throw new IOException("Failed to compute hash.", e);

    }

}
 
Example 16
Project: cryptotrader   File: BitflyerContext.java   View Source Code Vote up 3 votes
@Override
public void onBoardsSnapshot(String product, Board value) {

    if (value == null) {
        return;
    }

    String key = StringUtils.trimToEmpty(product);

    Instant timestamp = getNow();

    realtimeBoards.put(key, Optional.of(new BitflyerBoard(timestamp, value)));

}
 
Example 17
Project: cryptotrader   File: BitbankContext.java   View Source Code Vote up 3 votes
@VisibleForTesting
BigDecimal fetchBalance(Key key, CurrencyType currency) {

    if (currency == null) {
        return null;
    }

    String id = StringUtils.trimToEmpty(currency.name());

    Key k = Key.build(key).instrument(WILDCARD).build();

    List<BitbankAsset> assets = trimToEmpty(listCached(BitbankAsset.class, k, () -> {

        Assets a = getLocalApi().getAsset();

        if (a == null || ArrayUtils.isEmpty(a.assets)) {
            return emptyList();
        }

        return Stream.of(a.assets).filter(Objects::nonNull)
                .map(BitbankAsset::new).collect(toList());

    }));

    return trimToEmpty(assets).stream()
            .filter(Objects::nonNull)
            .filter(a -> id.equalsIgnoreCase(a.getId()))
            .findFirst().map(BitbankAsset::getBalance).orElse(null);

}
 
Example 18
Project: bootstrap   File: DataTableAttributes.java   View Source Code Vote up 2 votes
/**
 * Return the search filter from the query parameters.
 * 
 * @param uriInfo
 *            filter data.
 * @return the search filter from the query parameters. May be
 *         <code>null</code>.
 */
public static String getSearch(final UriInfo uriInfo) {
	return StringUtils.trimToEmpty(ObjectUtils.defaultIfNull(uriInfo.getQueryParameters().getFirst("q"),
			uriInfo.getQueryParameters().getFirst(SEARCH)));
}
 
Example 19
Project: cryptotrader   File: CompositeEstimator.java   View Source Code Vote up 2 votes
@VisibleForTesting
Estimation estimate(Context context, Request request, BiFunction<Context, Request, Estimation> function) {

    List<Composite> composites = request.getEstimatorComposites();

    if (CollectionUtils.isEmpty(composites)) {
        return BAIL;
    }

    Request.RequestBuilder builder = Request.build(request);

    BigDecimal price = ONE;

    BigDecimal confidence = ONE;

    for (Composite composite : composites) {

        String site = StringUtils.trimToEmpty(composite.getSite());

        if (site.length() <= 1) {
            return BAIL;
        }

        BinaryOperator<BigDecimal> operator = OPERATORS.get(site.charAt(0));

        if (operator == null) {
            return BAIL;
        }

        String instrument = composite.getInstrument();

        Request elementRequest = builder.site(site.substring(1)).instrument(instrument).build();

        Estimation estimation = function.apply(context, elementRequest);

        if (estimation == null || estimation.getPrice() == null || estimation.getConfidence() == null) {
            return BAIL;
        }

        price = operator.apply(price, estimation.getPrice());

        confidence = confidence.multiply(estimation.getConfidence());

    }

    return Estimation.builder().price(price).confidence(confidence).build();

}
 
Example 20
Project: cryptotrader   File: CoincheckContext.java   View Source Code Vote up 2 votes
@VisibleForTesting
String executePrivate(RequestType type, String url, Map<String, String> parameters, String data) throws Exception {

    String apiKey = getStringProperty("api.id", null);
    String secret = getStringProperty("api.secret", null);

    if (StringUtils.isEmpty(apiKey) || StringUtils.isEmpty(secret)) {
        return null;
    }

    String result;

    synchronized (lastNonce) {

        long currNonce = 0;

        while (currNonce <= lastNonce.get()) {

            TimeUnit.MILLISECONDS.sleep(1);

            currNonce = getNow().toEpochMilli();

        }

        lastNonce.set(currNonce);

        String path = url + buildQueryParameter(parameters);
        String nonce = String.valueOf(currNonce);
        String message = nonce + path + StringUtils.trimToEmpty(data);
        String hash = computeHash("HmacSHA256", secret.getBytes(), message.getBytes());

        Map<String, String> headers = new LinkedHashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("ACCESS-KEY", apiKey);
        headers.put("ACCESS-NONCE", nonce);
        headers.put("ACCESS-SIGNATURE", hash);

        result = request(type, path, headers, data);


    }

    return result;

}