index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/http/HttpService.java
|
/********************************************************************************
* Copyright (c) 2019 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.http;
import java.io.IOException;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.el.MethodNotFoundException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.security.auth.x500.X500Principal;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import eu.arrowhead.common.CommonConstants;
import eu.arrowhead.common.SSLProperties;
import eu.arrowhead.common.Utilities;
import eu.arrowhead.common.exception.AuthException;
import eu.arrowhead.common.exception.UnavailableServerException;
@Component
public class HttpService {
//=================================================================================================
// members
private static final String ERROR_MESSAGE_PART_PKIX_PATH = "PKIX path";
private static final String ERROR_MESSAGE_PART_SUBJECT_ALTERNATIVE_NAMES = "doesn't match any of the subject alternative names";
private static final List<HttpMethod> NOT_SUPPORTED_METHODS = List.of(HttpMethod.HEAD, HttpMethod.OPTIONS, HttpMethod.TRACE);
private final Logger logger = LogManager.getLogger(HttpService.class);
@Value(CommonConstants.$DISABLE_HOSTNAME_VERIFIER_WD)
private boolean disableHostnameVerifier;
@Value(CommonConstants.$HTTP_CLIENT_CONNECTION_TIMEOUT_WD)
private int connectionTimeout;
@Value(CommonConstants.$HTTP_CLIENT_SOCKET_TIMEOUT_WD)
private int socketTimeout;
@Value(CommonConstants.$HTTP_CLIENT_CONNECTION_MANAGER_TIMEOUT_WD)
private int connectionManagerTimeout;
@Autowired
private SSLProperties sslProperties;
private String clientName;
@Autowired
private ArrowheadHttpClientResponseErrorHandler errorHandler;
private RestTemplate template;
private RestTemplate sslTemplate;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
@PostConstruct
public void init() throws Exception { //NOSONAR Exception needs here
logger.debug("Initializing HttpService...");
template = createTemplate(null);
SSLContext sslContext;
if (sslProperties.isSslEnabled()) {
try {
sslContext = createSSLContext();
} catch (final KeyManagementException | UnrecoverableKeyException | KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException ex) {
// it's initialization so we just logging the exception then let the application die
logger.error("Error while creating SSL context: {}", ex.getMessage());
logger.debug("Exception", ex);
throw ex;
}
sslTemplate = createTemplate(sslContext);
}
logger.debug("HttpService is initialized.");
}
//-------------------------------------------------------------------------------------------------
public <T,P> ResponseEntity<T> sendRequest(final UriComponents uri, final HttpMethod method, final Class<T> responseType, final P payload, final SSLContext givenContext) {
Assert.notNull(method, "Request method is not defined.");
logger.debug("Sending {} request to: {}", method, uri);
if (uri == null) {
logger.error("sendRequest() is called with null URI.");
throw new NullPointerException("HttpService.sendRequest method received null URI. This most likely means the invoking Core System could not " +
"fetch the service of another Core System from the Service Registry!");
}
if (NOT_SUPPORTED_METHODS.contains(method)) {
throw new MethodNotFoundException("Invalid method type was given to the HttpService.sendRequest() method.");
}
final boolean secure = CommonConstants.HTTPS.equalsIgnoreCase(uri.getScheme());
if (secure && sslTemplate == null) {
logger.debug("sendRequest(): secure request sending was invoked in insecure mode.");
throw new AuthException("SSL Context is not set, but secure request sending was invoked. An insecure module can not send requests to secure modules.", HttpStatus.SC_UNAUTHORIZED);
}
RestTemplate usedTemplate;
if (secure) { // to make SonarQube happy
usedTemplate = givenContext != null ? createTemplate(givenContext) : sslTemplate;
} else {
usedTemplate = template;
}
final HttpEntity<P> entity = getHttpEntity(payload);
try {
return usedTemplate.exchange(uri.toUri(), method, entity, responseType);
} catch (final ResourceAccessException ex) {
if (ex.getMessage().contains(ERROR_MESSAGE_PART_PKIX_PATH)) {
logger.error("The system at {} is not part of the same certificate chain of trust!", uri.toUriString());
throw new AuthException("The system at " + uri.toUriString() + " is not part of the same certificate chain of trust!", HttpStatus.SC_UNAUTHORIZED, ex);
} else if (ex.getMessage().contains(ERROR_MESSAGE_PART_SUBJECT_ALTERNATIVE_NAMES)) {
logger.error("The certificate of the system at {} does not contain the specified IP address or DNS name as a Subject Alternative Name.", uri.toString());
throw new AuthException("The certificate of the system at " + uri.toString() + " does not contain the specified IP address or DNS name as a Subject Alternative Name.");
} else {
logger.error("UnavailableServerException occurred at {}", uri.toUriString());
logger.debug("Exception", ex);
throw new UnavailableServerException("Could not get any response from: " + uri.toUriString(), HttpStatus.SC_SERVICE_UNAVAILABLE, ex);
}
}
}
//-------------------------------------------------------------------------------------------------
public <T,P> ResponseEntity<T> sendRequest(final UriComponents uri, final HttpMethod method, final Class<T> responseType, final P payload) {
return sendRequest(uri, method, responseType, payload, null);
}
//-------------------------------------------------------------------------------------------------
public <T> ResponseEntity<T> sendRequest(final UriComponents uri, final HttpMethod method, final Class<T> responseType, final SSLContext givenContext) {
return sendRequest(uri, method, responseType, null, givenContext);
}
//-------------------------------------------------------------------------------------------------
public <T> ResponseEntity<T> sendRequest(final UriComponents uri, final HttpMethod method, final Class<T> responseType) {
return sendRequest(uri, method, responseType, null, null);
}
//=================================================================================================
// assistant methods
//-------------------------------------------------------------------------------------------------
private <P> HttpEntity<P> getHttpEntity(final P payload) {
final MultiValueMap<String,String> headers = new LinkedMultiValueMap<>();
headers.put(HttpHeaders.ACCEPT, Arrays.asList(MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE));
if (payload != null) {
headers.put(HttpHeaders.CONTENT_TYPE, Collections.singletonList(MediaType.APPLICATION_JSON_VALUE));
}
return payload != null ? new HttpEntity<>(payload, headers) : new HttpEntity<>(headers);
}
//-------------------------------------------------------------------------------------------------
private RestTemplate createTemplate(final SSLContext sslContext) {
final HttpClient client = createClient(sslContext);
final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client) {
// This modification is needed to reuse already established connections in subsequent HTTP calls.
@Override
protected HttpContext createHttpContext(final HttpMethod httpMethod, final URI uri) {
final HttpContext context = new HttpClientContext(new BasicHttpContext());
if (!Utilities.isEmpty(clientName)) {
context.setAttribute(HttpClientContext.USER_TOKEN, new X500Principal(clientName));
}
return context;
}
};
final RestTemplate restTemplate = new RestTemplate(factory);
restTemplate.setErrorHandler(errorHandler);
return restTemplate;
}
//-------------------------------------------------------------------------------------------------
private HttpClient createClient(final SSLContext sslContext) {
HttpClient client;
if (sslContext == null) {
client = HttpClients.custom().setDefaultRequestConfig(createRequestConfig())
.build();
} else {
SSLConnectionSocketFactory socketFactory;
if (disableHostnameVerifier) { // just for testing, DO NOT USE this in a production environment
final HostnameVerifier allHostsAreAllowed = (hostname, session) -> true; //NOSONAR
socketFactory = new SSLConnectionSocketFactory(sslContext, allHostsAreAllowed);
} else {
socketFactory = new SSLConnectionSocketFactory(sslContext);
}
client = HttpClients.custom().setDefaultRequestConfig(createRequestConfig())
.setSSLSocketFactory(socketFactory)
.build();
}
return client;
}
//-------------------------------------------------------------------------------------------------
private SSLContext createSSLContext() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException, UnrecoverableKeyException {
final String messageNotDefined = " is not defined.";
Assert.isTrue(!Utilities.isEmpty(sslProperties.getKeyStoreType()), CommonConstants.KEYSTORE_TYPE + messageNotDefined);
Assert.notNull(sslProperties.getKeyStore(), CommonConstants.KEYSTORE_PATH + messageNotDefined);
Assert.isTrue(sslProperties.getKeyStore().exists(), CommonConstants.KEYSTORE_PATH + " file is not found.");
Assert.notNull(sslProperties.getKeyStorePassword(), CommonConstants.KEYSTORE_PASSWORD + messageNotDefined);
Assert.notNull(sslProperties.getKeyPassword(), CommonConstants.KEY_PASSWORD + messageNotDefined);
Assert.notNull(sslProperties.getTrustStore(), CommonConstants.TRUSTSTORE_PATH + messageNotDefined);
Assert.isTrue(sslProperties.getTrustStore().exists(), CommonConstants.TRUSTSTORE_PATH + " file is not found.");
Assert.notNull(sslProperties.getTrustStorePassword(), CommonConstants.TRUSTSTORE_PASSWORD + messageNotDefined);
final KeyStore keystore = KeyStore.getInstance(sslProperties.getKeyStoreType());
keystore.load(sslProperties.getKeyStore().getInputStream(), sslProperties.getKeyStorePassword().toCharArray());
final X509Certificate certFromKeyStore = Utilities.getSystemCertFromKeyStore(keystore);
clientName = certFromKeyStore.getSubjectDN().getName();
return new SSLContextBuilder().loadTrustMaterial(sslProperties.getTrustStore().getURL(), sslProperties.getTrustStorePassword().toCharArray())
.loadKeyMaterial(keystore, sslProperties.getKeyPassword().toCharArray())
.setKeyStoreType(sslProperties.getKeyStoreType())
.build();
}
//-------------------------------------------------------------------------------------------------
private RequestConfig createRequestConfig() {
return RequestConfig.custom().setConnectTimeout(connectionTimeout)
.setSocketTimeout(socketTimeout)
.setConnectionRequestTimeout(connectionManagerTimeout)
.build();
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/security/AccessControlFilter.java
|
/********************************************************************************
* Copyright (c) 2019 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.security;
import java.io.IOException;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.HttpStatus;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import eu.arrowhead.common.CommonConstants;
import eu.arrowhead.common.SecurityUtilities;
import eu.arrowhead.common.Utilities;
import eu.arrowhead.common.exception.ArrowheadException;
import eu.arrowhead.common.exception.AuthException;
import eu.arrowhead.common.filter.ArrowheadFilter;
import eu.arrowhead.common.filter.thirdparty.MultiReadRequestWrapper;
public abstract class AccessControlFilter extends ArrowheadFilter {
//=================================================================================================
// members
@Resource(name = CommonConstants.ARROWHEAD_CONTEXT)
protected Map<String,Object> arrowheadContext;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
log.debug("Checking access in AccessControlFilter...");
try {
final MultiReadRequestWrapper requestWrapper = new MultiReadRequestWrapper((HttpServletRequest) request);
final String requestTarget = Utilities.stripEndSlash(requestWrapper.getRequestURL().toString());
final String requestJSON = requestWrapper.getCachedBody();
final Map<String,String[]> queryParams = requestWrapper.getParameterMap();
final String clientCN = getCertificateCNFromRequest(requestWrapper);
if (clientCN == null) {
log.error("Unauthorized access: {}", requestTarget);
throw new AuthException("Unauthorized access: " + requestTarget);
}
checkClientAuthorized(clientCN, requestWrapper.getMethod(), requestTarget, requestJSON, queryParams);
log.debug("Using MultiReadRequestWrapper in the filter chain from now...");
chain.doFilter(requestWrapper, response);
} catch (final ArrowheadException ex) {
handleException(ex, response);
}
} else {
chain.doFilter(request, response);
}
}
//=================================================================================================
// assistant methods
//-------------------------------------------------------------------------------------------------
protected void checkClientAuthorized(final String clientCN, final String method, final String requestTarget, final String requestJSON, final Map<String,String[]> queryParams) {
if (!Utilities.isKeyStoreCNArrowheadValid(clientCN)) {
log.debug("{} is not a valid common name, access denied!", clientCN);
throw new AuthException(clientCN + " is unauthorized to access " + requestTarget, HttpStatus.SC_UNAUTHORIZED, requestTarget);
}
// All requests from the local cloud are allowed
if (!Utilities.isKeyStoreCNArrowheadValid(clientCN, getServerCloudCN())) {
log.debug("{} is unauthorized to access {}", clientCN, requestTarget);
throw new AuthException(clientCN + " is unauthorized to access " + requestTarget, HttpStatus.SC_UNAUTHORIZED, requestTarget);
}
}
//-------------------------------------------------------------------------------------------------
protected String getServerCloudCN() {
final String serverCN = (String) arrowheadContext.get(CommonConstants.SERVER_COMMON_NAME);
final String[] serverFields = serverCN.split("\\.", 2); // serverFields contains: coreSystemName, cloudName.operator.arrowhead.eu
Assert.isTrue(serverFields.length >= 2, "Server common name is invalid: " + serverCN);
return serverFields[1];
}
//-------------------------------------------------------------------------------------------------
@Nullable
private String getCertificateCNFromRequest(final HttpServletRequest request) {
return SecurityUtilities.getCertificateCNFromRequest(request);
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/token/TokenSecurityFilter.java
|
/********************************************************************************
* Copyright (c) 2019 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.token;
import java.io.IOException;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.springframework.lang.Nullable;
import eu.arrowhead.common.CommonConstants;
import eu.arrowhead.common.SecurityUtilities;
import eu.arrowhead.common.Utilities;
import eu.arrowhead.common.exception.ArrowheadException;
import eu.arrowhead.common.exception.AuthException;
import eu.arrowhead.common.filter.ArrowheadFilter;
import eu.arrowhead.common.token.TokenUtilities.TokenInfo;
public abstract class TokenSecurityFilter extends ArrowheadFilter {
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
log.debug("Checking access in TokenSecurityFilter...");
try {
final HttpServletRequest httpRequest = (HttpServletRequest) request;
final String requestTarget = Utilities.stripEndSlash(httpRequest.getRequestURL().toString());
final String clientCN = getCertificateCNFromRequest(httpRequest);
if (clientCN == null) {
log.error("Unauthorized access: {}", requestTarget);
throw new AuthException("Unauthorized access: " + requestTarget);
}
final String token = httpRequest.getParameter(CommonConstants.REQUEST_PARAM_TOKEN);
if (Utilities.isEmpty(token)) {
log.error("Unauthorized access: {}, no token is specified", requestTarget);
throw new AuthException("Unauthorized access: " + requestTarget + ", no token is specified");
}
checkToken(clientCN, token, requestTarget);
} catch (final ArrowheadException ex) {
handleException(ex, response);
return;
}
}
chain.doFilter(request, response);
}
//=================================================================================================
// assistant methods
//-------------------------------------------------------------------------------------------------
protected abstract PrivateKey getMyPrivateKey();
//-------------------------------------------------------------------------------------------------
protected abstract PublicKey getAuthorizationPublicKey();
//-------------------------------------------------------------------------------------------------
protected TokenSecurityFilter() {}
//-------------------------------------------------------------------------------------------------
protected TokenInfo checkToken(final String clientCN, final String token, final String requestTarget) {
final String clientName = clientCN.split("\\.")[0];
final TokenInfo tokenInfo = TokenUtilities.validateTokenAndExtractTokenInfo(token, getAuthorizationPublicKey(), getMyPrivateKey()); // expiration (if set) is already checked in this method
if (!clientName.equalsIgnoreCase(tokenInfo.getConsumerName())) {
log.error("Client CN ({}) and token information ({}) is mismatched at: {}", clientCN, tokenInfo.getConsumerName(), requestTarget);
throw new AuthException("Unauthorized accesss: " + requestTarget + ", invalid token.");
}
return tokenInfo;
}
//-------------------------------------------------------------------------------------------------
@Nullable
private String getCertificateCNFromRequest(final HttpServletRequest request) {
return SecurityUtilities.getCertificateCNFromRequest(request);
}
}
|
0
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common
|
java-sources/ai/aitia/arrowhead-core-common-essentials-java-spring/4.6.0.0/eu/arrowhead/common/token/TokenUtilities.java
|
/********************************************************************************
* Copyright (c) 2019 AITIA
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* AITIA - implementation
* Arrowhead Consortia - conceptualization
********************************************************************************/
package eu.arrowhead.common.token;
import java.security.PrivateKey;
import java.security.PublicKey;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jose4j.jwa.AlgorithmConstraints;
import org.jose4j.jwa.AlgorithmConstraints.ConstraintType;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.MalformedClaimException;
import org.jose4j.jwt.ReservedClaimNames;
import org.jose4j.jwt.consumer.InvalidJwtException;
import org.jose4j.jwt.consumer.JwtConsumer;
import org.jose4j.jwt.consumer.JwtConsumerBuilder;
import org.springframework.util.Assert;
import eu.arrowhead.common.CommonConstants;
import eu.arrowhead.common.Utilities;
import eu.arrowhead.common.exception.AuthException;
import eu.arrowhead.common.exception.InvalidParameterException;
public class TokenUtilities {
//=================================================================================================
// members
private static final Logger logger = LogManager.getLogger(TokenUtilities.class);
private static final AlgorithmConstraints JWS_ALG_CONSTRAINTS = new AlgorithmConstraints(ConstraintType.WHITELIST, CommonConstants.JWS_SIGN_ALG);
private static final AlgorithmConstraints JWE_ALG_CONSTRAINTS = new AlgorithmConstraints(ConstraintType.WHITELIST, CommonConstants.JWE_KEY_MANAGEMENT_ALG);
private static final AlgorithmConstraints JWE_ENCRYPTION_CONSTRAINTS = new AlgorithmConstraints(ConstraintType.WHITELIST, CommonConstants.JWE_ENCRYPTION_ALG);
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public static TokenInfo validateTokenAndExtractTokenInfo(final String token, final PublicKey authorizationPublicKey, final PrivateKey privateKey) {
logger.debug("validateTokenAndExtractTokenInfo started...");
Assert.notNull(authorizationPublicKey, "Authorization public key is null.");
Assert.notNull(privateKey, "Private key is null.");
if (Utilities.isEmpty(token)) {
throw new InvalidParameterException("No token is provided.");
}
final JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireJwtId()
.setRequireNotBefore()
.setEnableRequireEncryption()
.setEnableRequireIntegrity()
.setExpectedIssuer(CommonConstants.CORE_SYSTEM_AUTHORIZATION)
.setDecryptionKey(privateKey)
.setVerificationKey(authorizationPublicKey)
.setJwsAlgorithmConstraints(JWS_ALG_CONSTRAINTS)
.setJweAlgorithmConstraints(JWE_ALG_CONSTRAINTS)
.setJweContentEncryptionAlgorithmConstraints(JWE_ENCRYPTION_CONSTRAINTS)
.build();
try {
final JwtClaims claims = jwtConsumer.processToClaims(token);
final String consumerName = extractConsumerName(claims);
final String service = extractService(claims);
final String interfaceName = extractInterfaceName(claims);
final Long expirationTime = extractExpirationTime(claims);
return new TokenInfo(consumerName, service, interfaceName, expirationTime);
} catch (final InvalidJwtException ex) {
logger.debug("Token processing is failed: {}", ex.getMessage());
logger.debug(ex);
throw new AuthException("Token processing is failed", ex);
}
}
//=================================================================================================
// assistant methods
//-------------------------------------------------------------------------------------------------
private TokenUtilities() {
throw new UnsupportedOperationException();
}
//-------------------------------------------------------------------------------------------------
private static String extractConsumerName(final JwtClaims claims) throws InvalidJwtException {
if (!claims.hasClaim(CommonConstants.JWT_CLAIM_CONSUMER_ID)) {
throw new InvalidJwtException("Missing consumer information.", null, null, null);
}
try {
final String consumerId = claims.getStringClaimValue(CommonConstants.JWT_CLAIM_CONSUMER_ID);
final String[] parts = consumerId.split("\\.");
return parts[0];
} catch (final MalformedClaimException ex) {
throw new InvalidJwtException("Invalid consumer information.", null, ex, null);
}
}
//-------------------------------------------------------------------------------------------------
private static String extractService(final JwtClaims claims) throws InvalidJwtException {
if (!claims.hasClaim(CommonConstants.JWT_CLAIM_SERVICE_ID)) {
throw new InvalidJwtException("Missing service information.", null, null, null);
}
try {
return claims.getStringClaimValue(CommonConstants.JWT_CLAIM_SERVICE_ID);
} catch (final MalformedClaimException ex) {
throw new InvalidJwtException("Invalid service information.", null, ex, null);
}
}
//-------------------------------------------------------------------------------------------------
private static String extractInterfaceName(final JwtClaims claims) throws InvalidJwtException {
if (!claims.hasClaim(CommonConstants.JWT_CLAIM_INTERFACE_ID)) {
throw new InvalidJwtException("Missing interface information.", null, null, null);
}
try {
return claims.getStringClaimValue(CommonConstants.JWT_CLAIM_INTERFACE_ID);
} catch (final MalformedClaimException ex) {
throw new InvalidJwtException("Invalid interface information.", null, ex, null);
}
}
//-------------------------------------------------------------------------------------------------
private static Long extractExpirationTime(final JwtClaims claims) throws InvalidJwtException {
try {
return claims.hasClaim(ReservedClaimNames.EXPIRATION_TIME) ? claims.getExpirationTime().getValueInMillis() : null;
} catch (final MalformedClaimException ex) {
// never happens at this point
throw new InvalidJwtException("Invalid expiration time.", null, ex, null);
}
}
//=================================================================================================
// nested classes
//-------------------------------------------------------------------------------------------------
public static class TokenInfo {
//=================================================================================================
// members
private final String consumerName;
private final String service;
private final String interfaceName;
private final Long endOfValidity;
//=================================================================================================
// methods
//-------------------------------------------------------------------------------------------------
public TokenInfo(final String consumerName, final String service, final String interfaceName, final Long endOfValidity) {
this.consumerName = consumerName;
this.service = service;
this.interfaceName = interfaceName;
this.endOfValidity = endOfValidity;
}
//-------------------------------------------------------------------------------------------------
public String getConsumerName() { return consumerName; }
public String getService() { return service; }
public String getInterfaceName() { return interfaceName; }
public Long getEndOfValidity() { return endOfValidity; }
public boolean hasEndOfValidity() { return endOfValidity != null && endOfValidity.longValue() > 0; }
//-------------------------------------------------------------------------------------------------
@Override
public String toString() {
return "TokenInfo [consumerName=" + consumerName + ", service=" + service + ", interfaceName=" + interfaceName + ", endOfValidity=" + endOfValidity + "]";
}
}
}
|
0
|
java-sources/ai/ancf/lmos/arc-gemini-client/0.104.0/ai/ancf/lmos/arc/client
|
java-sources/ai/ancf/lmos/arc-gemini-client/0.104.0/ai/ancf/lmos/arc/client/gemini/ByteMapper.java
|
// SPDX-FileCopyrightText: 2024 Deutsche Telekom AG
//
// SPDX-License-Identifier: Apache-2.0
package ai.ancf.lmos.arc.client.gemini;
import com.google.cloud.vertexai.api.Part;
import com.google.cloud.vertexai.generativeai.PartMaker;
/**
* Workaround for the mapping kotlin byte arrays to java byte arrays.
*/
public class ByteMapper {
/**
* Maps a byte array to a Part.
*
* @param mimeType The mime type of the byte array.
* @param data The byte array.
* @return a Gemini Part instance.
*/
public static Part map(String mimeType, byte[] data) {
return PartMaker.fromMimeTypeAndData(mimeType, data);
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai
|
java-sources/ai/api/libai/1.6.12/ai/api/AIConfiguration.java
|
package ai.api;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2017 by Speaktoit, Inc. (https://www.speaktoit.com) https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
***********************************************************************************************************************/
import java.io.UnsupportedEncodingException;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com) https://www.api.ai
*
* *********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
***********************************************************************************************************************/
import java.net.Proxy;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import ai.api.util.StringUtils;
/**
* AI service configuration
*/
public class AIConfiguration implements Cloneable {
private static final String SERVICE_PROD_URL = "https://api.api.ai/v1/";
protected static final String CURRENT_PROTOCOL_VERSION = "20150910";
protected static final String QUESTION_ENDPOINT = "query";
protected static final String USER_ENTITIES_ENDPOINT = "userEntities";
protected static final String CONTEXTS_ENDPOINT = "contexts";
private final String apiKey;
private final SupportedLanguages language;
private String serviceUrl;
/**
* Protocol version used for api queries. Can be changed if old protocol version required.
*
* See https://docs.api.ai/v20/docs/versioning for details
*/
private String protocolVersion;
private boolean writeSoundLog = false;
private Proxy proxy;
/**
* Create configuration with given client access token and language.
*
* See https://docs.api.ai/v20/docs/authentication for details
*
* @param clientAccessToken An agent unique key. Cannot be <code>null</code>
* @param language An agent language
*/
public AIConfiguration(final String clientAccessToken, final SupportedLanguages language) {
if (clientAccessToken == null) {
throw new IllegalArgumentException("clientAccessToken");
}
this.apiKey = clientAccessToken;
this.language = language != null ? language : SupportedLanguages.DEFAULT;
protocolVersion = CURRENT_PROTOCOL_VERSION;
serviceUrl = SERVICE_PROD_URL;
}
/**
* Create configuration with given client access token.
*
* See https://docs.api.ai/v20/docs/authentication for details
*
* @param clientAccessToken An agent unique key. Cannot be <code>null</code>
*/
public AIConfiguration(final String clientAccessToken) {
this(clientAccessToken, null);
}
/**
* Get client access key
*/
public String getApiKey() {
return apiKey;
}
/**
* Get client agent language
*
* @return Never <code>null</code>
*/
public String getLanguage() {
return language.languageTag;
}
/**
* Get api.ai agent language
*
* @return Never <code>null</code>
*/
public String getApiAiLanguage() {
return language.apiaiLanguage;
}
/**
* This flag is for testing purposes ONLY. Don't change it.
*
* @param writeSoundLog value, indicating recorded sound will be saved in storage (if possible)
*/
public void setWriteSoundLog(final boolean writeSoundLog) {
this.writeSoundLog = writeSoundLog;
}
/**
* This flag is for testing purposes ONLY. Don't use it in your code.
*
* @return value, indicating recorded sound will be saved in storage (if possible)
*/
public boolean isWriteSoundLog() {
return writeSoundLog;
}
/**
* Check list of supported protocol versions on the api.ai website.
*
* @return protocol version in YYYYMMDD format
*/
public String getProtocolVersion() {
return protocolVersion;
}
/**
* Set protocol version for API queries. Must be in YYYYMMDD format. This option for special cases
* only, should not be used in usual cases.
*
* @param protocolVersion Protocol version in YYYYMMDD format or empty string for the oldest
* version. Check list of supported protocol versions on the api.ai website.
*/
public void setProtocolVersion(final String protocolVersion) {
this.protocolVersion = protocolVersion;
}
/**
* Set API service url. Used primarily for test requests.
*/
public void setServiceUrl(final String serviceUrl) {
this.serviceUrl = serviceUrl;
}
/**
* Get connection proxy information. If <code>null</code> then direct connection would be used.
*/
public Proxy getProxy() {
return proxy;
}
/**
* Set connection proxy information.
*
* @param proxy If <code>null</code> then direct connection would be used.
*/
public void setProxy(final Proxy proxy) {
this.proxy = proxy;
}
/**
* Clone the configuration
*/
public AIConfiguration clone() {
try {
AIConfiguration result = (AIConfiguration) super.clone();
return result;
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
String getQuestionUrl(final String sessionId) {
if (StringUtils.isEmpty(protocolVersion)) {
return String.format("%s%s?sessionId=%s", serviceUrl, QUESTION_ENDPOINT, sessionId);
} else {
return String.format("%s%s?v=%s&sessionId=%s", serviceUrl, QUESTION_ENDPOINT, protocolVersion,
sessionId);
}
}
String getUserEntitiesEndpoint(final String sessionId) {
if (StringUtils.isEmpty(protocolVersion)) {
return String.format("%s%s?sessionId=%s", serviceUrl, USER_ENTITIES_ENDPOINT, sessionId);
} else {
return String.format("%s%s?v=%s&sessionId=%s", serviceUrl, USER_ENTITIES_ENDPOINT,
protocolVersion, sessionId);
}
}
String getContextsUrl(final String sessionId) {
return getContextsUrl(sessionId, "");
}
String getContextsUrl(final String sessionId, final String suffix) {
StringBuilder result = new StringBuilder();
result.append(serviceUrl).append(CONTEXTS_ENDPOINT);
if (!StringUtils.isEmpty(suffix)) {
try {
result.append("/").append(URLEncoder.encode(suffix, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// This is unexpected due to encoding value is defined as constant string
throw new RuntimeException(e);
}
}
result.append("?");
if (!StringUtils.isEmpty(protocolVersion)) {
result.append("v=").append(protocolVersion).append("&");
}
result.append("sessionId=").append(sessionId);
return result.toString();
}
private static Map<String, SupportedLanguages> STRING_TO_LANGUAGE = new HashMap<>();
/**
* Currently supported languages
*/
public static enum SupportedLanguages {
ChineseChina("zh-CN"),
ChineseHongKong("zh-HK"),
ChineseTaiwan("zh-TW"),
English("en"),
EnglishUS("en-US", "en"),
EnglishGB("en-GB", "en"),
Dutch("nl"),
French("fr"),
German("de"),
Italian("it"),
Japanese("ja"),
Korean("ko"),
Portuguese("pt"),
PortugueseBrazil("pt-BR"),
Russian("ru"),
Spanish("es"),
Ukrainian("uk");
/**
* Default language value
*/
public static SupportedLanguages DEFAULT = SupportedLanguages.English;
private final String languageTag;
private final String apiaiLanguage;
SupportedLanguages(final String languageTag) {
this(languageTag, languageTag);
}
SupportedLanguages(final String languageTag, final String apiaiLanguage) {
assert languageTag != null;
assert apiaiLanguage != null;
this.languageTag = languageTag;
this.apiaiLanguage = apiaiLanguage;
SupportedLanguages retValue = STRING_TO_LANGUAGE.put(languageTag, this);
assert retValue == null : "languageTag duplicates";
}
public static SupportedLanguages fromLanguageTag(final String languageTag) {
SupportedLanguages result = STRING_TO_LANGUAGE.get(languageTag);
return result != null ? result : DEFAULT;
}
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai
|
java-sources/ai/api/libai/1.6.12/ai/api/AIDataService.java
|
package ai.api;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com) https://www.api.ai
*
* *********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
***********************************************************************************************************************/
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import ai.api.util.IOUtils;
import ai.api.util.StringUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.net.*;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ai.api.http.HttpClient;
import ai.api.model.AIContext;
import ai.api.model.AIRequest;
import ai.api.model.AIResponse;
import ai.api.model.Entity;
import ai.api.model.Status;
/**
* Do simple requests to the AI Service
*/
public class AIDataService {
private static final Logger logger = LoggerFactory.getLogger(AIDataService.class);
private static final AIServiceContext UNDEFINED_SERVICE_CONTEXT = null;
private static final String REQUEST_METHOD_POST = "POST";
private static final String REQUEST_METHOD_DELETE = "DELETE";
private static final String REQUEST_METHOD_GET = "GET";
private static final String DEFAULT_REQUEST_METHOD = REQUEST_METHOD_POST;
/**
* Cannot be <code>null</code>
*/
private final static Gson GSON = GsonFactory.getDefaultFactory().getGson();
/**
* Cannot be <code>null</code>
*/
private final AIConfiguration config;
/**
* Cannot be <code>null</code>
*/
private final AIServiceContext defaultServiceContext;
/**
* Create new service for given configuration and some predefined service context
*
* @param config Service configuration data. Cannot be <code>null</code>
* @param serviceContext Service context. If <code>null</code> then new context will be created
* @throws IllegalArgumentException If config parameter is null
*/
public AIDataService(final AIConfiguration config, final AIServiceContext serviceContext) {
if (config == null) {
throw new IllegalArgumentException("config should not be null");
}
this.config = config.clone();
if (serviceContext == null) {
this.defaultServiceContext = new AIServiceContextBuilder().generateSessionId().build();
} else {
this.defaultServiceContext = serviceContext;
}
}
/**
* Create new service with unique context for given configuration
*
* @param config Service configuration data. Cannot be <code>null</code>
* @throws IllegalArgumentException If config parameter is null
*/
public AIDataService(final AIConfiguration config) {
this(config, null);
}
/**
* @return Current context used in each request. Never <code>null</code>
*/
public AIServiceContext getContext() {
return defaultServiceContext;
}
/**
* Make request to the AI service.
*
* @param request request object to the service. Cannot be <code>null</code>
* @return response object from service. Never <code>null</code>
*/
public AIResponse request(final AIRequest request) throws AIServiceException {
return request(request, (RequestExtras) null);
}
/**
* Make request to the AI service.
*
* @param request request object to the service. Cannot be <code>null</code>
* @param serviceContext custom service context that should be used instead of the default context
* @return response object from service. Never <code>null</code>
*/
public AIResponse request(final AIRequest request, final AIServiceContext serviceContext)
throws AIServiceException {
return request(request, (RequestExtras) null, serviceContext);
}
/**
* Make request to the AI service.
*
* @param request request object to the service. Cannot be <code>null</code>
* @param requestExtras object that can hold additional contexts and entities
* @return response object from service. Never <code>null</code>
*/
public AIResponse request(final AIRequest request, final RequestExtras requestExtras)
throws AIServiceException {
return request(request, requestExtras, UNDEFINED_SERVICE_CONTEXT);
}
/**
* Make request to the AI service.
*
* @param request request object to the service. Cannot be <code>null</code>
* @param requestExtras object that can hold additional contexts and entities
* @param serviceContext custom service context that should be used instead of the default context
* @return response object from service. Never <code>null</code>
*/
public AIResponse request(final AIRequest request, final RequestExtras requestExtras,
final AIServiceContext serviceContext) throws AIServiceException {
if (request == null) {
throw new IllegalArgumentException("Request argument must not be null");
}
logger.debug("Start request");
try {
if (StringUtils.isEmpty(request.getLanguage())) {
request.setLanguage(config.getApiAiLanguage());
}
if (StringUtils.isEmpty(request.getSessionId())) {
request.setSessionId(getSessionId(serviceContext));
}
if (StringUtils.isEmpty(request.getTimezone())) {
request.setTimezone(getTimeZone(serviceContext));
}
Map<String, String> additionalHeaders = null;
if (requestExtras != null) {
fillRequest(request, requestExtras);
additionalHeaders = requestExtras.getAdditionalHeaders();
}
final String queryData = GSON.toJson(request);
final String response = doTextRequest(config.getQuestionUrl(request.getSessionId()),
queryData, additionalHeaders);
if (StringUtils.isEmpty(response)) {
throw new AIServiceException(
"Empty response from ai service. Please check configuration and Internet connection.");
}
logger.debug("Response json: " + response.replaceAll("[\r\n]+", " "));
final AIResponse aiResponse = GSON.fromJson(response, AIResponse.class);
if (aiResponse == null) {
throw new AIServiceException(
"API.AI response parsed as null. Check debug log for details.");
}
if (aiResponse.isError()) {
throw new AIServiceException(aiResponse);
}
aiResponse.cleanup();
return aiResponse;
} catch (final MalformedURLException e) {
logger.error("Malformed url should not be raised", e);
throw new AIServiceException("Wrong configuration. Please, connect to API.AI Service support",
e);
} catch (final JsonSyntaxException je) {
throw new AIServiceException(
"Wrong service answer format. Please, connect to API.AI Service support", je);
}
}
/**
* Make requests to the AI service with voice data.
*
* @param voiceStream voice data stream for recognition. Cannot be <code>null</code>
* @return response object from service. Never <code>null</code>
* @throws AIServiceException
*/
public AIResponse voiceRequest(final InputStream voiceStream) throws AIServiceException {
return voiceRequest(voiceStream, new RequestExtras());
}
/**
* Make requests to the AI service with voice data.
*
* @param voiceStream voice data stream for recognition. Cannot be <code>null</code>
* @param aiContexts additional contexts for request
* @return response object from service. Never <code>null</code>
* @throws AIServiceException
*/
public AIResponse voiceRequest(final InputStream voiceStream, final List<AIContext> aiContexts)
throws AIServiceException {
return voiceRequest(voiceStream, new RequestExtras(aiContexts, null));
}
/**
* Make requests to the AI service with voice data.
*
* @param voiceStream voice data stream for recognition. Cannot be <code>null</code>
* @param requestExtras object that can hold additional contexts and entities
* @return response object from service. Never <code>null</code>
* @throws AIServiceException
*/
public AIResponse voiceRequest(final InputStream voiceStream, final RequestExtras requestExtras)
throws AIServiceException {
return voiceRequest(voiceStream, requestExtras, UNDEFINED_SERVICE_CONTEXT);
}
/**
* Make requests to the AI service with voice data.
*
* @param voiceStream voice data stream for recognition. Cannot be <code>null</code>
* @param requestExtras object that can hold additional contexts and entities
* @param serviceContext custom service context that should be used instead of the default context
* @return response object from service. Never <code>null</code>
* @throws AIServiceException
*/
public AIResponse voiceRequest(final InputStream voiceStream, final RequestExtras requestExtras,
final AIServiceContext serviceContext) throws AIServiceException {
assert voiceStream != null;
logger.debug("Start voice request");
try {
final AIRequest request = new AIRequest();
request.setLanguage(config.getApiAiLanguage());
request.setSessionId(getSessionId(serviceContext));
request.setTimezone(getTimeZone(serviceContext));
Map<String, String> additionalHeaders = null;
if (requestExtras != null) {
fillRequest(request, requestExtras);
additionalHeaders = requestExtras.getAdditionalHeaders();
}
final String queryData = GSON.toJson(request);
logger.debug("Request json: " + queryData);
final String response = doSoundRequest(voiceStream, queryData, additionalHeaders);
if (StringUtils.isEmpty(response)) {
throw new AIServiceException("Empty response from ai service. Please check configuration.");
}
logger.debug("Response json: " + response);
final AIResponse aiResponse = GSON.fromJson(response, AIResponse.class);
if (aiResponse == null) {
throw new AIServiceException(
"API.AI response parsed as null. Check debug log for details.");
}
if (aiResponse.isError()) {
throw new AIServiceException(aiResponse);
}
aiResponse.cleanup();
return aiResponse;
} catch (final MalformedURLException e) {
logger.error("Malformed url should not be raised", e);
throw new AIServiceException("Wrong configuration. Please, connect to AI Service support", e);
} catch (final JsonSyntaxException je) {
throw new AIServiceException(
"Wrong service answer format. Please, connect to API.AI Service support", je);
}
}
/**
* Forget all old contexts
*
* @return true if operation succeed, false otherwise
*/
@Deprecated
public boolean resetContexts() {
final AIRequest cleanRequest = new AIRequest();
cleanRequest.setQuery("empty_query_for_resetting_contexts"); // TODO remove it after protocol
// fix
cleanRequest.setResetContexts(true);
try {
final AIResponse response = request(cleanRequest);
return !response.isError();
} catch (final AIServiceException e) {
logger.error("Exception while contexts clean.", e);
return false;
}
}
/**
* Retrieves the list of all currently active contexts for a session
*
* @return List of contexts, or empty list if there is no any active contexts
* @throws AIServiceException
*/
public List<AIContext> getActiveContexts() throws AIServiceException {
return getActiveContexts(UNDEFINED_SERVICE_CONTEXT);
}
/**
* Retrieves the list of all currently active contexts for a session
*
* @param serviceContext custom service context that should be used instead of the default context
* @return List of contexts, or empty list if there is no any active contexts
* @throws AIServiceException
*/
public List<AIContext> getActiveContexts(final AIServiceContext serviceContext)
throws AIServiceException {
try {
return doRequest(ApiActiveContextListResponse.class,
config.getContextsUrl(getSessionId(serviceContext)), REQUEST_METHOD_GET);
} catch (BadResponseStatusException e) {
throw new AIServiceException(e.response);
}
}
/**
* Retrieves the specified context for a session
*
* @param contextName The context name
* @return <code>null</code> if context not found
* @throws AIServiceException
*/
public AIContext getActiveContext(final String contextName) throws AIServiceException {
return getActiveContext(contextName, UNDEFINED_SERVICE_CONTEXT);
}
/**
* Retrieves the specified context for a session
*
* @param contextName The context name
* @param serviceContext custom service context that should be used instead of the default context
* @return <code>null</code> if context not found
* @throws AIServiceException
*/
public AIContext getActiveContext(final String contextName, final AIServiceContext serviceContext)
throws AIServiceException {
try {
return doRequest(AIContext.class,
config.getContextsUrl(getSessionId(serviceContext), contextName), REQUEST_METHOD_GET);
} catch (BadResponseStatusException e) {
if (e.response.getStatus().getCode() == 404) {
return null;
} else {
throw new AIServiceException(e.response);
}
}
}
/**
* Adds new active contexts for a session
*
* @param contexts Iterable collection of contexts
* @return List of added context names, or empty list if no contexts were added
* @throws AIServiceException
*/
public List<String> addActiveContext(final Iterable<AIContext> contexts)
throws AIServiceException {
return addActiveContext(contexts, UNDEFINED_SERVICE_CONTEXT);
}
/**
* Adds new active contexts for a session
*
* @param contexts Iterable collection of contexts
* @param serviceContext custom service context that should be used instead of the default context
* @return List of added context names, or empty list if no contexts were added
* @throws AIServiceException
*/
public List<String> addActiveContext(final Iterable<AIContext> contexts,
final AIServiceContext serviceContext) throws AIServiceException {
ApiActiveContextNamesResponse response;
try {
response = doRequest(contexts, ApiActiveContextNamesResponse.class,
config.getContextsUrl(getSessionId(serviceContext)), REQUEST_METHOD_POST);
return response.names;
} catch (BadResponseStatusException e) {
throw new AIServiceException(e.response);
}
}
/**
* Adds new active context for a session
*
* @param context New context
* @return Name of added context
* @throws AIServiceException
*/
public String addActiveContext(final AIContext context) throws AIServiceException {
return addActiveContext(context, UNDEFINED_SERVICE_CONTEXT);
}
/**
* Adds new active context for a session
*
* @param context New context
* @param serviceContext custom service context that should be used instead of the default context
* @return Name of added context
* @throws AIServiceException
*/
public String addActiveContext(final AIContext context, final AIServiceContext serviceContext)
throws AIServiceException {
ApiActiveContextNamesResponse response;
try {
response = doRequest(context, ApiActiveContextNamesResponse.class,
config.getContextsUrl(getSessionId(serviceContext)), REQUEST_METHOD_POST);
return response.names != null && response.names.size() > 0 ? response.names.get(0) : null;
} catch (BadResponseStatusException e) {
throw new AIServiceException(e.response);
}
}
/**
* Deletes all active contexts for a session
*
* @throws AIServiceException
*/
public void resetActiveContexts() throws AIServiceException {
resetActiveContexts(UNDEFINED_SERVICE_CONTEXT);
}
/**
* Deletes all active contexts for a session
*
* @param serviceContext custom service context that should be used instead of the default context
* @throws AIServiceException
*/
public void resetActiveContexts(final AIServiceContext serviceContext) throws AIServiceException {
try {
doRequest(AIResponse.class, config.getContextsUrl(getSessionId(serviceContext)),
REQUEST_METHOD_DELETE);
} catch (BadResponseStatusException e) {
throw new AIServiceException(e.response);
}
}
/**
* Deletes the specified context for a session
*
* @param contextName The context name
* @return <code>false</code> if context was not delete, <code>true</code> in otherwise case
* @throws AIServiceException
*/
public boolean removeActiveContext(final String contextName) throws AIServiceException {
return removeActiveContext(contextName, UNDEFINED_SERVICE_CONTEXT);
}
/**
* Deletes the specified context for a session
*
* @param contextName The context name
* @param serviceContext custom service context that should be used instead of the default context
* @return <code>false</code> if context was not delete, <code>true</code> in otherwise case
* @throws AIServiceException
*/
public boolean removeActiveContext(final String contextName,
final AIServiceContext serviceContext) throws AIServiceException {
try {
doRequest(AIResponse.class, config.getContextsUrl(getSessionId(serviceContext), contextName),
REQUEST_METHOD_DELETE);
return true;
} catch (BadResponseStatusException e) {
if (e.response.getStatus().getCode() == 404) {
return false;
} else {
throw new AIServiceException(e.response);
}
}
}
/**
* Add new entity to an agent entity list
*
* @param userEntity new entity data
* @return response object from service. Never <code>null</code>
* @throws AIServiceException
*/
public AIResponse uploadUserEntity(final Entity userEntity) throws AIServiceException {
return uploadUserEntity(userEntity, UNDEFINED_SERVICE_CONTEXT);
}
/**
* Add new entity to an agent entity list
*
* @param userEntity new entity data
* @param serviceContext custom service context that should be used instead of the default context
* @return response object from service. Never <code>null</code>
* @throws AIServiceException
*/
public AIResponse uploadUserEntity(final Entity userEntity, AIServiceContext serviceContext)
throws AIServiceException {
return uploadUserEntities(Collections.singleton(userEntity), serviceContext);
}
/**
* Add a bunch of new entity to an agent entity list
*
* @param userEntities collection of a new entity data
* @return response object from service. Never <code>null</code>
* @throws AIServiceException
*/
public AIResponse uploadUserEntities(final Collection<Entity> userEntities)
throws AIServiceException {
return uploadUserEntities(userEntities, UNDEFINED_SERVICE_CONTEXT);
}
/**
* Add a bunch of new entity to an agent entity list
*
* @param userEntities collection of a new entity data
* @param serviceContext custom service context that should be used instead of the default context
* @return response object from service. Never <code>null</code>
* @throws AIServiceException
*/
public AIResponse uploadUserEntities(final Collection<Entity> userEntities,
AIServiceContext serviceContext) throws AIServiceException {
if (userEntities == null || userEntities.size() == 0) {
throw new AIServiceException("Empty entities list");
}
final String requestData = GSON.toJson(userEntities);
try {
final String response =
doTextRequest(config.getUserEntitiesEndpoint(getSessionId(serviceContext)), requestData);
if (StringUtils.isEmpty(response)) {
throw new AIServiceException(
"Empty response from ai service. Please check configuration and Internet connection.");
}
logger.debug("Response json: " + response);
final AIResponse aiResponse = GSON.fromJson(response, AIResponse.class);
if (aiResponse == null) {
throw new AIServiceException(
"API.AI response parsed as null. Check debug log for details.");
}
if (aiResponse.isError()) {
throw new AIServiceException(aiResponse);
}
aiResponse.cleanup();
return aiResponse;
} catch (final MalformedURLException e) {
logger.error("Malformed url should not be raised", e);
throw new AIServiceException("Wrong configuration. Please, connect to AI Service support", e);
} catch (final JsonSyntaxException je) {
throw new AIServiceException(
"Wrong service answer format. Please, connect to API.AI Service support", je);
}
}
/**
* @param requestJson Cannot be <code>null</code>
* @param serviceContext custom service context that should be used instead of the default context
* @return Response string
* @throws MalformedURLException
* @throws AIServiceException
*/
protected String doTextRequest(final String requestJson, AIServiceContext serviceContext)
throws MalformedURLException, AIServiceException {
return doTextRequest(config.getQuestionUrl(getSessionId(serviceContext)), requestJson);
}
/**
* @param requestJson Cannot be <code>null</code>
* @return Response string
* @throws MalformedURLException
* @throws AIServiceException
*/
protected String doTextRequest(final String requestJson)
throws MalformedURLException, AIServiceException {
return doTextRequest(requestJson, UNDEFINED_SERVICE_CONTEXT);
}
/**
* @param endpoint Cannot be <code>null</code>
* @param requestJson Cannot be <code>null</code>
* @return Response string
* @throws MalformedURLException
* @throws AIServiceException
*/
protected String doTextRequest(final String endpoint, final String requestJson)
throws MalformedURLException, AIServiceException {
return doTextRequest(endpoint, requestJson, null);
}
/**
* @param endpoint Cannot be <code>null</code>
* @param requestJson Cannot be <code>null</code>
* @param additionalHeaders
* @return Response string
* @throws MalformedURLException
* @throws AIServiceException
*/
protected String doTextRequest(final String endpoint, final String requestJson,
final Map<String, String> additionalHeaders)
throws MalformedURLException, AIServiceException {
// TODO call doRequest method
assert endpoint != null;
assert requestJson != null;
HttpURLConnection connection = null;
try {
final URL url = new URL(endpoint);
final String queryData = requestJson;
logger.debug("Request json: " + queryData);
if (config.getProxy() != null) {
connection = (HttpURLConnection) url.openConnection(config.getProxy());
} else {
connection = (HttpURLConnection) url.openConnection();
}
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.addRequestProperty("Authorization", "Bearer " + config.getApiKey());
connection.addRequestProperty("Content-Type", "application/json; charset=utf-8");
connection.addRequestProperty("Accept", "application/json");
if (additionalHeaders != null) {
for (final Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
connection.addRequestProperty(entry.getKey(), entry.getValue());
}
}
connection.connect();
final BufferedOutputStream outputStream =
new BufferedOutputStream(connection.getOutputStream());
IOUtils.writeAll(queryData, outputStream);
outputStream.close();
final InputStream inputStream = new BufferedInputStream(connection.getInputStream());
final String response = IOUtils.readAll(inputStream);
inputStream.close();
return response;
} catch (final IOException e) {
if (connection != null) {
try {
final InputStream errorStream = connection.getErrorStream();
if (errorStream != null) {
final String errorString = IOUtils.readAll(errorStream);
logger.debug(errorString);
return errorString;
} else {
throw new AIServiceException("Can't connect to the api.ai service.", e);
}
} catch (final IOException ex) {
logger.warn("Can't read error response", ex);
}
}
logger.error(
"Can't make request to the API.AI service. Please, check connection settings and API access token.",
e);
throw new AIServiceException(
"Can't make request to the API.AI service. Please, check connection settings and API access token.",
e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
/**
* Method extracted for testing purposes
*
* @param voiceStream Cannot be <code>null</code>
* @param queryData Cannot be <code>null</code>
*/
protected String doSoundRequest(final InputStream voiceStream, final String queryData)
throws MalformedURLException, AIServiceException {
return doSoundRequest(voiceStream, queryData, null, UNDEFINED_SERVICE_CONTEXT);
}
/**
* Method extracted for testing purposes
*
* @param voiceStream Cannot be <code>null</code>
* @param queryData Cannot be <code>null</code>
*/
protected String doSoundRequest(final InputStream voiceStream, final String queryData,
final Map<String, String> additionalHeaders)
throws MalformedURLException, AIServiceException {
return doSoundRequest(voiceStream, queryData, additionalHeaders, UNDEFINED_SERVICE_CONTEXT);
}
/**
* Method extracted for testing purposes
*
* @param voiceStream Cannot be <code>null</code>
* @param queryData Cannot be <code>null</code>
*/
protected String doSoundRequest(final InputStream voiceStream, final String queryData,
final Map<String, String> additionalHeaders, final AIServiceContext serviceContext)
throws MalformedURLException, AIServiceException {
// TODO call doRequest method
assert voiceStream != null;
assert queryData != null;
HttpURLConnection connection = null;
HttpClient httpClient = null;
try {
final URL url = new URL(config.getQuestionUrl(getSessionId(serviceContext)));
logger.debug("Connecting to {}", url);
if (config.getProxy() != null) {
connection = (HttpURLConnection) url.openConnection(config.getProxy());
} else {
connection = (HttpURLConnection) url.openConnection();
}
connection.addRequestProperty("Authorization", "Bearer " + config.getApiKey());
connection.addRequestProperty("Accept", "application/json");
if (additionalHeaders != null) {
for (final Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
connection.addRequestProperty(entry.getKey(), entry.getValue());
}
}
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
httpClient = new HttpClient(connection);
httpClient.setWriteSoundLog(config.isWriteSoundLog());
httpClient.connectForMultipart();
httpClient.addFormPart("request", queryData);
httpClient.addFilePart("voiceData", "voice.wav", voiceStream);
httpClient.finishMultipart();
final String response = httpClient.getResponse();
return response;
} catch (final IOException e) {
if (httpClient != null) {
final String errorString = httpClient.getErrorString();
logger.debug(errorString);
if (!StringUtils.isEmpty(errorString)) {
return errorString;
} else if (e instanceof HttpRetryException) {
final AIResponse response = new AIResponse();
final int code = ((HttpRetryException) e).responseCode();
final Status status = Status.fromResponseCode(code);
status.setErrorDetails(((HttpRetryException) e).getReason());
response.setStatus(status);
throw new AIServiceException(response);
}
}
logger.error(
"Can't make request to the API.AI service. Please, check connection settings and API.AI keys.",
e);
throw new AIServiceException(
"Can't make request to the API.AI service. Please, check connection settings and API.AI keys.",
e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
protected <TResponse> TResponse doRequest(final Type responseType, final String endpoint,
final String method) throws AIServiceException, BadResponseStatusException {
return doRequest(responseType, endpoint, method, (Map<String, String>) null);
}
protected <TRequest, TResponse> TResponse doRequest(final TRequest request,
final Type responseType, final String endpoint, final String method)
throws AIServiceException, BadResponseStatusException {
return doRequest(request, responseType, endpoint, method, (Map<String, String>) null);
}
protected <TResponse> TResponse doRequest(final Type responseType, final String endpoint,
final String method, final Map<String, String> additionalHeaders)
throws AIServiceException, BadResponseStatusException {
return doRequest((Object) null, responseType, endpoint, method, additionalHeaders);
}
protected <TRequest, TResponse> TResponse doRequest(final TRequest request,
final Type responseType, final String endpoint, final String method,
final Map<String, String> additionalHeaders)
throws AIServiceException, BadResponseStatusException {
assert endpoint != null;
HttpURLConnection connection = null;
try {
final URL url = new URL(endpoint);
final String queryData = request != null ? GSON.toJson(request) : null;
final String requestMethod = method != null ? method : DEFAULT_REQUEST_METHOD;
logger.debug("Request json: " + queryData);
if (config.getProxy() != null) {
connection = (HttpURLConnection) url.openConnection(config.getProxy());
} else {
connection = (HttpURLConnection) url.openConnection();
}
if (queryData != null && !REQUEST_METHOD_POST.equals(requestMethod)) {
throw new AIServiceException("Non-empty request should be sent using POST method");
}
connection.setRequestMethod(requestMethod);
if (REQUEST_METHOD_POST.equals(requestMethod)) {
connection.setDoOutput(true);
}
connection.addRequestProperty("Authorization", "Bearer " + config.getApiKey());
connection.addRequestProperty("Content-Type", "application/json; charset=utf-8");
connection.addRequestProperty("Accept", "application/json");
if (additionalHeaders != null) {
for (final Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
connection.addRequestProperty(entry.getKey(), entry.getValue());
}
}
connection.connect();
if (queryData != null) {
final BufferedOutputStream outputStream =
new BufferedOutputStream(connection.getOutputStream());
IOUtils.writeAll(queryData, outputStream);
outputStream.close();
}
final InputStream inputStream = new BufferedInputStream(connection.getInputStream());
final String response = IOUtils.readAll(inputStream);
inputStream.close();
try {
AIResponse aiResponse = GSON.fromJson(response, AIResponse.class);
if (aiResponse.getStatus() != null && aiResponse.getStatus().getCode() != 200) {
throw new BadResponseStatusException(aiResponse);
}
} catch (JsonParseException e) {
// response is not in a expected format
}
return GSON.fromJson(response, responseType);
} catch (final IOException e) {
if (connection != null) {
try {
final InputStream errorStream = connection.getErrorStream();
if (errorStream != null) {
final String errorString = IOUtils.readAll(errorStream);
logger.debug(errorString);
throw new AIServiceException(errorString, e);
} else {
throw new AIServiceException("Can't connect to the api.ai service.", e);
}
} catch (final IOException ex) {
logger.warn("Can't read error response", ex);
}
}
logger.error(
"Can't make request to the API.AI service. Please, check connection settings and API access token.",
e);
throw new AIServiceException(
"Can't make request to the API.AI service. Please, check connection settings and API access token.",
e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
private void fillRequest(final AIRequest request, final RequestExtras requestExtras) {
assert request != null;
assert requestExtras != null;
if (requestExtras.hasContexts()) {
request.setContexts(requestExtras.getContexts());
}
if (requestExtras.hasEntities()) {
request.setEntities(requestExtras.getEntities());
}
if (requestExtras.getLocation() != null) {
request.setLocation(requestExtras.getLocation());
}
}
private String getSessionId(AIServiceContext serviceContext) {
return serviceContext != null ? serviceContext.getSessionId()
: defaultServiceContext.getSessionId();
}
private String getTimeZone(AIServiceContext serviceContext) {
TimeZone timeZone = serviceContext != null
? serviceContext.getTimeZone()
: defaultServiceContext.getTimeZone();
return (timeZone != null ? timeZone : Calendar.getInstance().getTimeZone()).getID();
}
private static class ApiActiveContextNamesResponse extends AIResponse {
private static final long serialVersionUID = 1L;
public List<String> names;
}
private static interface ApiActiveContextListResponse extends List<AIContext> {
}
private static class BadResponseStatusException extends Exception {
private static final long serialVersionUID = 1L;
private final AIResponse response;
public BadResponseStatusException(final AIResponse response) {
this.response = response;
}
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai
|
java-sources/ai/api/libai/1.6.12/ai/api/AIServiceContext.java
|
package ai.api;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2017 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
* *********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import java.util.TimeZone;
/**
* Contains environment specific information required for service request
*/
public interface AIServiceContext {
/**
* @return Session unique string value. Never <code>null</code>
*/
String getSessionId();
/**
* @return Client's time zone. If <code>null</code> then system default time zone
* will be assumed.
*/
TimeZone getTimeZone();
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai
|
java-sources/ai/api/libai/1.6.12/ai/api/AIServiceContextBuilder.java
|
package ai.api;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2017 by Speaktoit, Inc. (https://www.speaktoit.com) https://www.api.ai
*
* *********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
***********************************************************************************************************************/
import java.util.TimeZone;
import java.util.UUID;
/**
* Builds {@link AIServiceContext} to be used in {@link AIDataService}
*/
public class AIServiceContextBuilder {
private String sessionId;
private TimeZone timeZone;
/**
* Default builder constructor. Does not initialise any building options.
*/
public AIServiceContextBuilder() {}
/**
* @return Current sessionId value or <code>null</code> if value was not defined
*/
public String getSessionId() {
return sessionId;
}
/**
* Replace current session id with given value
*
* @param sessionId Unique string session id. Cannot be <code>null</code>
*
* @throws IllegalArgumentException Thrown if sessionId parameter value is null
*/
public AIServiceContextBuilder setSessionId(final String sessionId) {
if (sessionId == null) {
throw new IllegalArgumentException("sessionId cannot be null");
}
this.sessionId = sessionId;
return this;
}
/**
* Replace current session id with some new random value
*/
public AIServiceContextBuilder generateSessionId() {
this.sessionId = createRandomSessionId();
return this;
}
/**
* @return Current time zone value or <code>null</code> if value was not defined
*/
public TimeZone getTimeZone() {
return timeZone;
}
/**
* Replace current time zone with given value
*
* @param timeZone Time zone value. May be <code>null</code>
*/
public AIServiceContextBuilder setTimeZone(final TimeZone timeZone) {
this.timeZone = timeZone;
return this;
}
/**
* Use {@link AIServiceContextBuilder}.setTimeZone method insted
*/
@Deprecated()
public AIServiceContextBuilder setSessionId(final TimeZone timeZone) {
this.timeZone = timeZone;
return this;
}
/**
* Build new context instance
*
* @throws IllegalStateException Thrown if session id was not defined
*/
public AIServiceContext build() {
if (sessionId == null) {
throw new IllegalStateException("Session id is undefined");
}
return new PlainAIServiceContext(sessionId, timeZone);
}
public static AIServiceContext buildFromSessionId(String sessionId) {
return new AIServiceContextBuilder().setSessionId(sessionId).build();
}
private static String createRandomSessionId() {
return UUID.randomUUID().toString();
}
private static class PlainAIServiceContext implements AIServiceContext {
private final String sessionId;
private final TimeZone timeZone;
public PlainAIServiceContext(String sessionId, TimeZone timeZone) {
assert sessionId != null;
this.sessionId = sessionId;
this.timeZone = timeZone;
}
@Override
public String getSessionId() {
return sessionId;
}
@Override
public TimeZone getTimeZone() {
return timeZone;
}
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai
|
java-sources/ai/api/libai/1.6.12/ai/api/AIServiceException.java
|
package ai.api;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import ai.api.util.StringUtils;
import ai.api.model.AIResponse;
public class AIServiceException extends Exception {
private static final long serialVersionUID = 1L;
private final AIResponse aiResponse;
public AIServiceException() {
aiResponse = null;
}
public AIServiceException(final String detailMessage, final Throwable throwable) {
super(detailMessage, throwable);
aiResponse = null;
}
public AIServiceException(final String detailMessage) {
super(detailMessage);
aiResponse = null;
}
public AIServiceException(final AIResponse aiResponse) {
super();
this.aiResponse = aiResponse;
}
public AIResponse getResponse() {
return aiResponse;
}
@Override
public String getMessage() {
if ((aiResponse != null) && (aiResponse.getStatus() != null)) {
final String errorDetails = aiResponse.getStatus().getErrorDetails();
if (!StringUtils.isEmpty(errorDetails)) {
return errorDetails;
}
}
return super.getMessage();
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai
|
java-sources/ai/api/libai/1.6.12/ai/api/GsonFactory.java
|
package ai.api;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2016 by Speaktoit, Inc. (https://www.speaktoit.com) https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
***********************************************************************************************************************/
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import ai.api.model.GoogleAssistantResponseMessages.ResponseChatBubble;
import ai.api.model.ResponseMessage;
import ai.api.model.ResponseMessage.MessageType;
import ai.api.model.ResponseMessage.Platform;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Locale;
/**
* {@link Gson} object factory used in serialization
*/
public class GsonFactory {
private static final Gson SIMPLIFIED_GSON;
private static final Gson PROTOCOL_GSON;
private static final GsonFactory DEFAULT_FACTORY = new GsonFactory();
static {
GsonBuilder gsonBuilder = new GsonBuilder()
.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US).toPattern())
.registerTypeAdapter(ResponseMessage.class, new ResponseItemAdapter())
.registerTypeAdapter(ResponseMessage.MessageType.class, new ResponseMessageTypeAdapter())
.registerTypeAdapter(ResponseMessage.Platform.class, new ResponseMessagePlatformAdapter());
SIMPLIFIED_GSON = gsonBuilder.create();
gsonBuilder.registerTypeAdapter(ResponseMessage.ResponseSpeech.class, new ResponseSpeechAdapter());
gsonBuilder.registerTypeAdapter(ResponseChatBubble.class, new ResponseChatBubbleAdapter());
PROTOCOL_GSON = gsonBuilder.create();
}
/**
* Get a {@link Gson} object
*/
public Gson getGson() {
return PROTOCOL_GSON;
}
/**
* Create a default factory
*/
public static GsonFactory getDefaultFactory() {
return DEFAULT_FACTORY;
}
private static class ResponseMessagePlatformAdapter implements
JsonDeserializer<ResponseMessage.Platform>,
JsonSerializer<ResponseMessage.Platform> {
@Override
public JsonElement serialize(Platform src, Type typeOfT, JsonSerializationContext context) {
return context.serialize(src.getName());
}
@Override
public Platform deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
String name = json.getAsString();
if (name == null) {
return Platform.DEFAULT;
}
Platform result = Platform.fromName(name);
if (result == null) {
throw new JsonParseException(String.format("Unexpected platform name: %s", json));
}
return result;
}
}
private static class ResponseMessageTypeAdapter implements
JsonDeserializer<ResponseMessage.MessageType>,
JsonSerializer<ResponseMessage.MessageType> {
@Override
public JsonElement serialize(MessageType src, Type typeOfT, JsonSerializationContext context) {
return context.serialize(src.getCode() <= 4 ? src.getCode() : src.getName());
}
@Override
public MessageType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonPrimitive jsonValue = json.getAsJsonPrimitive();
MessageType result = null;
if (jsonValue.isNumber()) {
result = MessageType.fromCode(jsonValue.getAsInt());
} else {
result = MessageType.fromName(jsonValue.getAsString());
}
if (result == null) {
throw new JsonParseException(String.format("Unexpected message type value: %s", jsonValue));
}
return result;
}
}
private static class ResponseItemAdapter implements JsonDeserializer<ResponseMessage>,
JsonSerializer<ResponseMessage> {
@Override
public ResponseMessage deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
MessageType messageType = context.deserialize(json.getAsJsonObject().get("type"), MessageType.class);
return context.deserialize(json, messageType.getType());
}
@Override
public JsonElement serialize(ResponseMessage src, Type typeOfSrc,
JsonSerializationContext context) {
return context.serialize(src, src.getClass());
}
}
private static class ResponseSpeechAdapter implements JsonDeserializer<ResponseMessage>,
JsonSerializer<ResponseMessage> {
public ResponseMessage.ResponseSpeech deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
if (json.isJsonObject()) {
final JsonObject jsonObject = (JsonObject) json;
final JsonElement speechValue = jsonObject.get("speech");
if (speechValue.isJsonPrimitive()) {
JsonArray array = new JsonArray();
array.add(speechValue);
jsonObject.add("speech", array);
}
}
return SIMPLIFIED_GSON.fromJson(json, typeOfT);
}
@Override
public JsonElement serialize(ResponseMessage src, Type typeOfSrc, JsonSerializationContext context) {
return SIMPLIFIED_GSON.toJsonTree(src, ResponseMessage.class);
}
}
private static class ResponseChatBubbleAdapter implements JsonDeserializer<ResponseChatBubble>,
JsonSerializer<ResponseChatBubble> {
public ResponseChatBubble deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
if (json.isJsonObject()) {
final JsonObject jsonObject = (JsonObject) json;
if (jsonObject.has("textToSpeech")) {
JsonArray items = jsonObject.getAsJsonArray("items");
if (items == null) {
items = new JsonArray(1);
jsonObject.add("items", items);
}
JsonObject item = new JsonObject();
item.add("textToSpeech", jsonObject.get("textToSpeech"));
item.add("ssml", jsonObject.get("ssml"));
item.add("displayText", jsonObject.get("displayText"));
items.add(item);
}
}
return SIMPLIFIED_GSON.fromJson(json, typeOfT);
}
@Override
public JsonElement serialize(ResponseChatBubble src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject result = (JsonObject)SIMPLIFIED_GSON.toJsonTree(src, ResponseMessage.class);
JsonArray items = result.getAsJsonArray("items");
if ((items != null) && (items.size() == 1)) {
JsonObject item = (JsonObject)items.get(0);
result.add("textToSpeech", item.get("textToSpeech"));
result.add("ssml", item.get("ssml"));
result.add("displayText", item.get("displayText"));
result.remove("items");
}
return result;
}
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai
|
java-sources/ai/api/libai/1.6.12/ai/api/RequestExtras.java
|
package ai.api;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import java.util.List;
import java.util.Map;
import ai.api.model.AIContext;
import ai.api.model.AIRequest;
import ai.api.model.Entity;
import ai.api.model.Location;
/**
* Extra data for request
*/
public class RequestExtras {
private List<AIContext> contexts;
private List<Entity> entities;
private Boolean resetContexts;
private Map<String, String> additionalHeaders;
private Location location;
public RequestExtras() {
contexts = null;
entities = null;
}
public RequestExtras(final List<AIContext> contexts, final List<Entity> entities) {
this.contexts = contexts;
this.entities = entities;
}
public List<AIContext> getContexts() {
return contexts;
}
public void setContexts(final List<AIContext> contexts) {
this.contexts = contexts;
}
public List<Entity> getEntities() {
return entities;
}
public void setEntities(final List<Entity> entities) {
this.entities = entities;
}
public Boolean getResetContexts() {
return resetContexts;
}
public void setResetContexts(final boolean resetContexts) {
this.resetContexts = resetContexts;
}
public Map<String, String> getAdditionalHeaders() {
return additionalHeaders;
}
/**
* Additional headers to be passed to API.AI service. Must not be used in normal cases.
* @param additionalHeaders map with headers
*/
public void setAdditionalHeaders(final Map<String, String> additionalHeaders) {
this.additionalHeaders = additionalHeaders;
}
public Location getLocation() {
return location;
}
public void setLocation(final Location location) {
this.location = location;
}
public boolean hasContexts() {
if (contexts != null && !contexts.isEmpty()) {
return true;
}
return false;
}
public boolean hasEntities() {
if (entities != null && !entities.isEmpty()) {
return true;
}
return false;
}
public boolean hasAdditionalHeaders() {
if (additionalHeaders != null && !additionalHeaders.isEmpty()) {
return true;
}
return false;
}
public void copyTo(final AIRequest request) {
if (hasContexts()) {
request.setContexts(getContexts());
}
if (hasEntities()) {
request.setEntities(getEntities());
}
if (getResetContexts() != null) {
request.setResetContexts(getResetContexts());
}
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/http/HttpClient.java
|
package ai.api.http;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import ai.api.util.IOUtils;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpClient {
private static final Logger logger = LoggerFactory.getLogger(HttpClient.class);
private static final int CHUNK_LENGTH = 2048;
private static final int BUFFER_LENGTH = 4096;
/**
* Cannot be <code>null</code>
*/
private final HttpURLConnection connection;
private OutputStream os;
private final String delimiter = "--";
private final String boundary = "SwA" + Long.toString(System.currentTimeMillis()) + "SwA";
private boolean writeSoundLog;
/**
* @param connection Cannot be <code>null</code>
*/
public HttpClient(final HttpURLConnection connection) {
if (connection == null) {
throw new IllegalArgumentException("Connection cannot be null");
}
this.connection = connection;
}
public void connectForMultipart() throws IOException {
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
connection.setChunkedStreamingMode(CHUNK_LENGTH);
connection.connect();
os = connection.getOutputStream();
}
/**
* @param paramName Cannot be <code>null</code>
* @param value Cannot be <code>null</code>
* @throws IOException
*/
public void addFormPart(final String paramName, final String value) throws IOException {
os.write((delimiter + boundary + "\r\n").getBytes());
os.write("Content-Type: application/json\r\n".getBytes());
os.write(("Content-Disposition: form-data; name=\"" + paramName + "\"\r\n").getBytes());
os.write(("\r\n" + value + "\r\n").getBytes());
}
/**
* @param paramName Cannot be <code>null</code>
* @param fileName Cannot be <code>null</code>
* @param data Cannot be <code>null</code>
* @throws IOException
*/
public void addFilePart(final String paramName, final String fileName, final InputStream data) throws IOException {
os.write((delimiter + boundary + "\r\n").getBytes());
os.write(("Content-Disposition: form-data; name=\"" + paramName + "\"; filename=\"" + fileName + "\"\r\n").getBytes());
os.write(("Content-Type: audio/wav\r\n").getBytes());
//os.write( ("Content-Transfer-Encoding: binary\r\n" ).getBytes());
os.write("\r\n".getBytes());
logger.debug("Sound write start");
FileOutputStream outputStream = null;
if (writeSoundLog) {
final File cacheDir = new File(System.getProperty("java.io.tmpdir"));
if (!cacheDir.exists()) {
cacheDir.mkdirs();
}
logger.debug(cacheDir.getAbsolutePath());
final File soundFile = new File(cacheDir, "log.wav");
outputStream = new FileOutputStream(soundFile, false);
}
final byte[] buffer = new byte[BUFFER_LENGTH];
int bytesActuallyRead;
bytesActuallyRead = data.read(buffer, 0, buffer.length);
while (bytesActuallyRead >= 0) {
if (bytesActuallyRead > 0) {
os.write(buffer, 0, bytesActuallyRead);
if (writeSoundLog) {
outputStream.write(buffer, 0, bytesActuallyRead);
}
}
bytesActuallyRead = data.read(buffer, 0, buffer.length);
}
if (writeSoundLog) {
outputStream.close();
}
logger.debug("Sound write finished");
os.write("\r\n".getBytes());
}
public void finishMultipart() throws IOException {
os.write((delimiter + boundary + delimiter + "\r\n").getBytes());
os.close();
}
/**
* @return Response string. Never <code>null</code>
* @throws IOException
*/
public String getResponse() throws IOException {
final InputStream inputStream = new BufferedInputStream(connection.getInputStream());
final String response = IOUtils.readAll(inputStream);
inputStream.close();
return response;
}
public String getErrorString() {
try {
final InputStream inputStream = new BufferedInputStream(connection.getErrorStream());
final String response;
response = IOUtils.readAll(inputStream);
inputStream.close();
return response;
} catch (final IOException e) {
e.printStackTrace();
}
return null;
}
public void setWriteSoundLog(final boolean writeSoundLog) {
this.writeSoundLog = writeSoundLog;
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/model/AIContext.java
|
package ai.api.model;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2014 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.Map;
public class AIContext implements Serializable {
private static final long serialVersionUID = 1L;
@SerializedName("name")
private String name;
@SerializedName("parameters")
private Map<String, String> parameters;
@SerializedName("lifespan")
private Integer lifespan;
public AIContext() {
}
public AIContext(final String name) {
this.name = name;
}
/**
* Context name
*/
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
/**
* String parameters map
*/
public Map<String, String> getParameters() {
return parameters;
}
public void setParameters(final Map<String, String> parameters) {
this.parameters = parameters;
}
/**
* Lifespan of the context measured in requests
* @return count of requests context will live
*/
public Integer getLifespan() {
return lifespan;
}
/**
* Lifespan of the context measured in requests
* @param lifespan count of requests context will live
*/
public void setLifespan(final Integer lifespan) {
this.lifespan = lifespan;
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/model/AIError.java
|
package ai.api.model;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import ai.api.AIServiceException;
import java.io.Serializable;
public class AIError implements Serializable {
private static final long serialVersionUID = 1L;
private final String message;
@SuppressWarnings("unused")
private final AIResponse aiResponse;
private AIServiceException exception;
public AIError(final String message) {
aiResponse = null;
this.message = message;
}
public AIError(final AIServiceException e) {
aiResponse = e.getResponse();
message = e.getMessage();
exception = e;
}
public AIError(final AIResponse aiResponse) {
this.aiResponse = aiResponse;
if (aiResponse == null) {
message = "API.AI service returns empty result";
}
else if (aiResponse.getStatus() != null) {
message = aiResponse.getStatus().getErrorDetails();
} else {
message = "API.AI service returns error code with empty status";
}
}
public String getMessage() {
return message;
}
@Override
public String toString() {
if (exception != null) {
return exception.toString();
} else {
return message;
}
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/model/AIEvent.java
|
package ai.api.model;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2017 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
public class AIEvent implements Serializable {
private static final long serialVersionUID = 1L;
@SerializedName("name")
private String name;
@SerializedName("data")
private Map<String, String> data;
public AIEvent() {
}
public AIEvent(final String name) {
this.name = name;
}
/**
* Event name
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* String data map
*/
public Map<String, String> getData() {
return data;
}
public void setData(Map<String, String> data) {
this.data = data;
}
public void addDataField(String key, String value) {
if (data == null)
setData(new HashMap<String, String>());
data.put(key, value);
}
public void addDataField(Map<String, String> dataParams) {
if (data == null)
setData(new HashMap<String, String>());
data.putAll(dataParams);
}
public String getDataField(final String name) {
return getDataField(name, "");
}
public String getDataField(final String name, final String defaultValue) {
if (data.containsKey(name)) {
return data.get(name);
}
return defaultValue;
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/model/AIOriginalRequest.java
|
package ai.api.model;
import java.util.Map;
public class AIOriginalRequest {
private String source;
private Map<String, Object> data;
/**
* @return the request source name (Facebook Messenger, Slack, etc.)
*/
public final String getSource() {
return source;
}
/**
* Set the request source name (Facebook Messenger, Slack, etc.)
* @param source
*/
public final void setSource(String source) {
this.source = source;
}
/**
* Get map of additional data values
*/
public final Map<String,? extends Object> getData() {
return data;
}
/**
* Set map of additional data values
* @param data
*/
public final void setData(Map<String, ? extends Object> data) {
this.data = (Map<String,Object>)data;
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/model/AIOutputContext.java
|
package ai.api.model;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2014 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import com.google.gson.JsonElement;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.Map;
public class AIOutputContext implements Serializable {
private static final long serialVersionUID = 1L;
@SerializedName("name")
private String name;
@SerializedName("parameters")
private Map<String, JsonElement> parameters;
@SerializedName("lifespan")
private Integer lifespan;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public Map<String, JsonElement> getParameters() {
return parameters;
}
public void setParameters(final Map<String, JsonElement> parameters) {
this.parameters = parameters;
}
/**
* Lifespan of the context measured in requests
* @return count of requests context will live
*/
public Integer getLifespan() {
return lifespan;
}
/**
* Lifespan of the context measured in requests
* @param lifespan count of requests context will live
*/
public void setLifespan(final Integer lifespan) {
this.lifespan = lifespan;
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/model/AIRequest.java
|
package ai.api.model;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2014 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import ai.api.util.StringUtils;
public class AIRequest extends QuestionMetadata implements Serializable {
private static final long serialVersionUID = 1L;
@SerializedName("query")
private String[] query;
@SerializedName("confidence")
private float[] confidence;
@SerializedName("contexts")
private List<AIContext> contexts;
@SerializedName("resetContexts")
private Boolean resetContexts;
@SerializedName("event")
private AIEvent event;
private AIOriginalRequest originalRequest;
public AIRequest() {
}
public AIRequest(final String query) {
setQuery(query);
}
public void setQuery(final String query) {
this.query = StringUtils.isEmpty(query) ? null : new String[]{query};
confidence = null;
}
public void setQuery(final String[] query, final float[] confidence) {
if (query == null) {
throw new IllegalStateException("Query array must not be null");
}
if (confidence == null && query.length > 1) {
throw new IllegalStateException("Then confidences array is null, query must be one or zero item length");
}
if (confidence != null && query.length != confidence.length) {
throw new IllegalStateException("Query and confidence arrays must be equals size");
}
this.query = query;
this.confidence = confidence;
}
public float[] getConfidence() {
return confidence;
}
public void setConfidence(final float[] confidence) {
this.confidence = confidence;
}
public void setResetContexts(final Boolean resetContexts) {
this.resetContexts = resetContexts;
}
public Boolean getResetContexts() {
return resetContexts;
}
public void setContexts(final List<AIContext> contexts) {
this.contexts = contexts;
}
public void addContext(final AIContext aiContext) {
if (contexts == null) {
contexts = new ArrayList<>(1);
}
contexts.add(aiContext);
}
public void setEvent(AIEvent event) {
this.event = event;
}
/**
* Full request coming from the integrated platform (Facebook Messenger, Slack, etc.)
* @return <code>null</code> if request is not defined
*/
public final AIOriginalRequest getOriginalRequest() {
return originalRequest;
}
/**
* Set full request coming from the integrated platform (Facebook Messenger, Slack, etc.)
* @param originalRequest <code>null</code> if request is not defined
*/
public final void setOriginalRequest(AIOriginalRequest originalRequest) {
this.originalRequest = originalRequest;
}
@Override
public String toString() {
return String.format("AIRequest{query=%s, resetContexts=%s, language='%s', timezone='%s'}",
Arrays.toString(query),
resetContexts,
getLanguage(),
getTimezone());
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/model/AIResponse.java
|
package ai.api.model;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2014 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.Date;
public class AIResponse implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Unique identifier of the result.
*/
@SerializedName("id")
private String id;
@SerializedName("timestamp")
private Date timestamp;
@SerializedName("lang")
private String lang;
/**
* Result object
*/
@SerializedName("result")
private Result result;
@SerializedName("status")
private Status status;
@SerializedName("sessionId")
private String sessionId;
/**
* Unique identifier of the result.
*/
public String getId() {
return id;
}
public void setId(final String id) {
this.id = id;
}
/**
* Date and time of the request in UTC timezone using ISO-8601 format.
*/
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(final Date timestamp) {
this.timestamp = timestamp;
}
/**
* Agent's language.
* @return Language tag. See <a href="https://docs.api.ai/docs/languages">languages</a>
* for details
*/
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
/**
* Contains the results of the natual language processing.
*/
public Result getResult() {
return result;
}
public void setResult(final Result result) {
this.result = result;
}
/**
* Contains data on how the request succeeded or failed.
*/
public Status getStatus() {
return status;
}
public void setStatus(final Status status) {
this.status = status;
}
/**
* Session ID
*/
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public boolean isError() {
if (status != null && status.getCode() != null && status.getCode() >= 400) {
return true;
}
return false;
}
@Override
public String toString() {
return String.format("AIResponse{id='%s', timestamp=%s, result=%s, status=%s, sessionId=%s}",
id,
timestamp,
result,
status,
sessionId);
}
public void cleanup() {
if (result != null) {
result.trimParameters();
}
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/model/Entity.java
|
package ai.api.model;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
* ********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* User Entity what can be uploaded to the API.AI service and override (or extend) entities, described in agent.
* User Entities works only in specified session, and do not affect other sessions.
*/
public class Entity implements Serializable {
private static final long serialVersionUID = 1L;
@SerializedName("name")
private String name;
@SerializedName("entries")
private List<EntityEntry> entries;
@SerializedName("extend")
private Boolean extend;
@SerializedName("isEnum")
private Boolean isEnum;
public Entity() {
}
public Entity(final String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public List<EntityEntry> getEntries() {
return entries;
}
public void setEntries(final List<EntityEntry> entries) {
this.entries = entries;
}
public void addEntry(final EntityEntry entry) {
if (entries == null) {
entries = new ArrayList<>();
}
entries.add(entry);
}
public Boolean getExtend() {
return extend;
}
public void setExtend(final boolean extend) {
this.extend = extend;
}
public Boolean isEnum() {
return isEnum;
}
public void setIsEnum(final Boolean isEnum) {
this.isEnum = isEnum;
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/model/EntityEntry.java
|
package ai.api.model;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
public class EntityEntry implements Serializable {
private static final long serialVersionUID = 1L;
@SerializedName("value")
private String value;
@SerializedName("synonyms")
private List<String> synonyms;
public EntityEntry() {
}
public EntityEntry(final String value) {
this.value = value;
}
public EntityEntry(final String value, final List<String> synonyms) {
this.value = value;
this.synonyms = synonyms;
}
public EntityEntry(final String value, final String[] synonyms) {
this.value = value;
this.synonyms = Arrays.asList(synonyms);
}
public String getValue() {
return value;
}
public void setValue(final String value) {
this.value = value;
}
public List<String> getSynonyms() {
return synonyms;
}
public void setSynonyms(final List<String> synonyms) {
this.synonyms = synonyms;
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/model/Fulfillment.java
|
package ai.api.model;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2017 by Speaktoit, Inc. (https://www.speaktoit.com) https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
***********************************************************************************************************************/
import com.google.gson.JsonElement;
import com.google.gson.annotations.SerializedName;
import ai.api.util.StringUtils;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* Model class for <a href="https://docs.api.ai/docs/webhook#section-format-of-response-from-the-service"
* >webhook response</a>.
*/
public class Fulfillment implements Serializable {
private static final long serialVersionUID = 1L;
@SerializedName("speech")
private String speech;
@SerializedName("messages")
private List<ResponseMessage> messages;
@SerializedName("displayText")
private String displayText;
@SerializedName("data")
private Map<String, JsonElement> data;
@SerializedName("source")
private String source;
@SerializedName("contextOut")
private List<AIOutputContext> contextOut;
@SerializedName("followupEvent")
private AIEvent followupEvent;
/** Get voice response to the request */
public String getSpeech() {
return speech;
}
/** Set voice response to the request */
public void setSpeech(final String speech) {
this.speech = speech;
}
/** Get list of {@link ResponseMessage} objects */
public List<ResponseMessage> getMessages() {
return messages;
}
/** Set list of {@link ResponseMessage} objects */
public void setMessages(List<ResponseMessage> messages) {
this.messages = messages;
}
/** Set sequence of {@link ResponseMessage} objects */
public void setMessages(ResponseMessage... messages) {
setMessages(Arrays.asList(messages));
}
/**
* @deprecated this method name is a typo, use <code>setMessages</code> method instead
*/
@Deprecated
public void getMessages(List<ResponseMessage> messages) {
// TODO remove this method after major version change
setMessages(messages);
}
/** Get additional data required for performing the action on the client side. */
public Map<String, JsonElement> getData() {
return data;
}
/** Set additional data required for performing the action on the client side. */
public void setData(final Map<String, JsonElement> data) {
this.data = data;
}
/** Get text displayed on the user device screen. */
public String getDisplayText() {
return displayText;
}
/** Set text displayed on the user device screen. */
public void setDisplayText(final String displayText) {
this.displayText = displayText;
}
/** Get a data source */
public String getSource() {
return source;
}
/** Set a data source */
public void setSource(final String source) {
this.source = source;
}
/** Get list of context objects set after intent completion. */
public List<AIOutputContext> getContextOut() {
return contextOut;
}
/** Get context object by its name. */
public AIOutputContext getContext(final String name) {
if (StringUtils.isEmpty(name)) {
throw new IllegalArgumentException("name argument must be not empty");
}
if (contextOut == null) {
return null;
}
for (final AIOutputContext c : contextOut) {
if (name.equalsIgnoreCase(c.getName())) {
return c;
}
}
return null;
}
/** Set list of context objects set after intent completion. */
public void setContextOut(final List<AIOutputContext> contextOut) {
this.contextOut = contextOut;
}
/** Set sequence of context objects set after intent completion. */
public void setContextOut(final AIOutputContext... contextOut) {
setContextOut(Arrays.asList(contextOut));
}
/** Get follow up event to be triggered*/
public AIEvent getFollowupEvent() {
return followupEvent;
}
/** Set follow up event to be triggered */
public void setFollowupEvent(AIEvent followupEvent) {
this.followupEvent = followupEvent;
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/model/GoogleAssistantResponseMessages.java
|
package ai.api.model;
import java.util.List;
public abstract class GoogleAssistantResponseMessages extends ResponseMessage {
protected GoogleAssistantResponseMessages(MessageType type) {
super(type, Platform.GOOGLE);
}
public static class CardImage {
private String url;
/**
* @return the URL
*/
public final String getUrl() {
return url;
}
/**
* @param url the URL to set
*/
public final void setUrl(String url) {
this.url = url;
}
}
public static class OptionInfo {
private String key;
private List<String> synonyms;
/**
* @return the key
*/
public final String getKey() {
return key;
}
/**
* @param key the key to set
*/
public final void setKey(String key) {
this.key = key;
}
/**
* @return the synonyms
*/
public final List<String> getSynonyms() {
return synonyms;
}
/**
* @param synonyms the synonyms to set
*/
public final void setSynonyms(List<String> synonyms) {
this.synonyms = synonyms;
}
}
public static class CardItem {
private OptionInfo optionInfo;
private String title;
private String description;
private CardImage image;
/**
* @return the optionInfo
*/
public final OptionInfo getOptionInfo() {
return optionInfo;
}
/**
* @param optionInfo the optionInfo to set
*/
public final void setOptionInfo(OptionInfo optionInfo) {
this.optionInfo = optionInfo;
}
/**
* @return the title
*/
public final String getTitle() {
return title;
}
/**
* @param title the title to set
*/
public final void setTitle(String title) {
this.title = title;
}
/**
* @return the description
*/
public final String getDescription() {
return description;
}
/**
* @param description the description to set
*/
public final void setDescription(String description) {
this.description = description;
}
/**
* @return the image
*/
public final CardImage getImage() {
return image;
}
/**
* @param image the image to set
*/
public final void setImage(CardImage image) {
this.image = image;
}
}
public static class ResponseChatBubble extends GoogleAssistantResponseMessages {
private Boolean customizeAudio;
private List<Item> items;
public ResponseChatBubble() {
super(MessageType.CHAT_BUBBLE);
}
/**
* @return the customizeAudio
*/
public final Boolean getCustomizeAudio() {
return customizeAudio;
}
/**
* @param customizeAudio the customizeAudio to set
*/
public final void setCustomizeAudio(Boolean customizeAudio) {
this.customizeAudio = customizeAudio;
}
/**
* @return the items
*/
public final List<Item> getItems() {
return items;
}
/**
* @param items the items to set
*/
public final void setItems(List<Item> items) {
this.items = items;
}
public static class Item {
private String textToSpeech;
private String ssml;
private String displayText;
/**
* @return the textToSpeech
*/
public final String getTextToSpeech() {
return textToSpeech;
}
/**
* @param textToSpeech the textToSpeech to set
*/
public final void setTextToSpeech(String textToSpeech) {
this.textToSpeech = textToSpeech;
}
/**
* @return the SSML
*/
public final String getSsml() {
return ssml;
}
/**
* @param ssml the SSML to set
*/
public final void setSsml(String ssml) {
this.ssml = ssml;
}
/**
* @return the displayText
*/
public final String getDisplayText() {
return displayText;
}
/**
* @param displayText the displayText to set
*/
public final void setDisplayText(String displayText) {
this.displayText = displayText;
}
}
}
public static class ResponseBasicCard extends GoogleAssistantResponseMessages {
private String title;
private String subtitle;
private String formattedText;
private CardImage image;
private List<Button> buttons;
public ResponseBasicCard() {
super(MessageType.BASIC_CARD);
}
/**
* @return the title
*/
public final String getTitle() {
return title;
}
/**
* @param title the title to set
*/
public final void setTitle(String title) {
this.title = title;
}
/**
* @return the subtitle
*/
public final String getSubtitle() {
return subtitle;
}
/**
* @param subtitle the subtitle to set
*/
public final void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
/**
* @return the formattedText
*/
public final String getFormattedText() {
return formattedText;
}
/**
* @param formattedText the formattedText to set
*/
public final void setFormattedText(String formattedText) {
this.formattedText = formattedText;
}
/**
* @return the image
*/
public final CardImage getImage() {
return image;
}
/**
* @param image the image to set
*/
public final void setImage(CardImage image) {
this.image = image;
}
/**
* @return the buttons
*/
public final List<Button> getButtons() {
return buttons;
}
/**
* @param buttons the buttons to set
*/
public final void setButtons(List<Button> buttons) {
this.buttons = buttons;
}
public static class Button {
private String title;
private OpenUrlAction openUrlAction;
/**
* @return the title
*/
public final String getTitle() {
return title;
}
/**
* @param title the title to set
*/
public final void setTitle(String title) {
this.title = title;
}
/**
* @return the openUrlAction
*/
public final OpenUrlAction getOpenUrlAction() {
return openUrlAction;
}
/**
* @param openUrlAction the openUrlAction to set
*/
public final void setOpenUrlAction(OpenUrlAction openUrlAction) {
this.openUrlAction = openUrlAction;
}
}
public static class OpenUrlAction {
private String url;
/**
* @return the URL
*/
public final String getUrl() {
return url;
}
/**
* @param url the URL to set
*/
public final void setUrl(String url) {
this.url = url;
}
}
}
public static class ResponseListCard extends GoogleAssistantResponseMessages {
private String title;
private List<CardItem> items;
public ResponseListCard() {
super(MessageType.LIST_CARD);
}
/**
* @return the title
*/
public final String getTitle() {
return title;
}
/**
* @param title the title to set
*/
public final void setTitle(String title) {
this.title = title;
}
/**
* @return the items
*/
public final List<CardItem> getItems() {
return items;
}
/**
* @param items the items to set
*/
public final void setItems(List<CardItem> items) {
this.items = items;
}
}
public static class ResponseSuggestionChips extends GoogleAssistantResponseMessages {
private List<Suggestion> suggestions;
public ResponseSuggestionChips() {
super(MessageType.SUGGESTION_CHIPS);
}
/**
* @return the suggestions
*/
public final List<Suggestion> getSuggestions() {
return suggestions;
}
/**
* @param suggestions the suggestions to set
*/
public final void setSuggestions(List<Suggestion> suggestions) {
this.suggestions = suggestions;
}
public static class Suggestion {
private String title;
/**
* @return the title
*/
public final String getTitle() {
return title;
}
/**
* @param title the title to set
*/
public final void setTitle(String title) {
this.title = title;
}
}
}
public static class ResponseCarouselCard extends GoogleAssistantResponseMessages {
private List<CardItem> items;
public ResponseCarouselCard() {
super(MessageType.CAROUSEL_CARD);
}
/**
* @return the items
*/
public final List<CardItem> getItems() {
return items;
}
/**
* @param items the items to set
*/
public final void setItems(List<CardItem> items) {
this.items = items;
}
}
public static class ResponseLinkOutChip extends GoogleAssistantResponseMessages {
private String destinationName;
private String url;
public ResponseLinkOutChip() {
super(MessageType.LINK_OUT_CHIP);
}
/**
* @return the destinationName
*/
public final String getDestinationName() {
return destinationName;
}
/**
* @param destinationName the destinationName to set
*/
public final void setDestinationName(String destinationName) {
this.destinationName = destinationName;
}
/**
* @return the URL
*/
public final String getUrl() {
return url;
}
/**
* @param url the URL to set
*/
public final void setUrl(String url) {
this.url = url;
}
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/model/Location.java
|
package ai.api.model;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2017 by Speaktoit, Inc. (https://www.speaktoit.com) https://www.api.ai
*
* *********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
***********************************************************************************************************************/
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class Location implements Serializable {
private static final long serialVersionUID = 1L;
@SerializedName("latitude")
private final double latitude;
@SerializedName("longitude")
private final double longitude;
public Location(final double latitude, final double longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/model/Metadata.java
|
package ai.api.model;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class Metadata implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Name of the intent that produced this result
*/
@SerializedName("intentName")
private String intentName;
/**
* Id of the intent that produced this result
*/
@SerializedName("intentId")
private String intentId;
/**
* Indicates wheather webhook functionaly is enabled in the triggered intent.
*/
@SerializedName("webhookUsed")
private String webhookUsed;
/**
* Name of the intent that produced this result
*/
public String getIntentName() {
return intentName;
}
public void setIntentName(final String intentName) {
this.intentName = intentName;
}
/**
* Id of the intent that produced this result
*/
public String getIntentId() {
return intentId;
}
public void setIntentId(final String intentId) {
this.intentId = intentId;
}
/**
* Indicates wheather webhook functionaly is enabled in the triggered intent.
*/
public boolean isWebhookUsed() {
return webhookUsed != null ? Boolean.valueOf(webhookUsed) : false;
}
public void setWebhookUsed(boolean webhookUsed) {
this.webhookUsed = Boolean.toString(webhookUsed);
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/model/QuestionMetadata.java
|
package ai.api.model;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import ai.api.util.StringUtils;
public class QuestionMetadata implements Serializable {
private static final long serialVersionUID = 1L;
@SerializedName("timezone")
private String timezone;
@SerializedName("lang")
private String language;
@SerializedName("sessionId")
private String sessionId;
@SerializedName("entities")
private List<Entity> entities;
@SerializedName("location")
private Location location;
public String getTimezone() {
return timezone;
}
public void setTimezone(final String timezone) {
this.timezone = timezone;
}
public String getLanguage() {
return language;
}
public void setLanguage(final String language) {
if (StringUtils.isEmpty(language)) {
throw new IllegalArgumentException("language must not be null");
}
this.language = language;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(final String sessionId) {
this.sessionId = sessionId;
}
public List<Entity> getEntities() {
return entities;
}
public void setEntities(final List<Entity> entities) {
this.entities = entities;
}
public void addEntity(final Entity entity) {
if (entities == null) {
entities = new ArrayList<>();
}
entities.add(entity);
}
public Location getLocation() {
return location;
}
public void setLocation(final Location location) {
this.location = location;
}
@Override
public String toString() {
return String.format("QuestionMetadata{language='%s', timezone='%s'}", language, timezone);
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/model/ResponseMessage.java
|
package ai.api.model;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2016 by Speaktoit, Inc. (https://www.speaktoit.com) https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
***********************************************************************************************************************/
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.JsonObject;
import com.google.gson.annotations.Expose;
import ai.api.model.GoogleAssistantResponseMessages.ResponseBasicCard;
import ai.api.model.GoogleAssistantResponseMessages.ResponseCarouselCard;
import ai.api.model.GoogleAssistantResponseMessages.ResponseChatBubble;
import ai.api.model.GoogleAssistantResponseMessages.ResponseLinkOutChip;
import ai.api.model.GoogleAssistantResponseMessages.ResponseListCard;
import ai.api.model.GoogleAssistantResponseMessages.ResponseSuggestionChips;
/**
* Base model class for
* <a href="https://docs.api.ai/docs/query#section-message-objects">response message objects</a>.
*/
public abstract class ResponseMessage {
@Expose
private final MessageType type;
@Expose
private final Platform platform;
/**
* Constructor initializing message type code
* @param type Message type. Cannot be <code>null</code>.
*/
protected ResponseMessage(MessageType type) {
this(type, null);
}
/**
* Constructor initializing message type code and platform
* @param type Message type. Cannot be <code>null</code>.
* @param platform Platform type. If <code>null</code> then
* default value will be used
*/
protected ResponseMessage(MessageType type, Platform platform) {
assert type != null;
this.type = type;
this.platform = platform != null ? platform : Platform.DEFAULT;
}
/**
* Holds the message type integer code and related {@link Type}
*/
public static enum MessageType {
/** Text response message object */
SPEECH(0, "message", ResponseSpeech.class),
/** Card message object */
CARD(1, "card", ResponseCard.class),
/** Quick replies message object */
QUICK_REPLY(2, "quick_reply", ResponseQuickReply.class),
/** Image message object */
IMAGE(3, "image", ResponseImage.class),
/** Custom payload message object */
PAYLOAD(4, "custom_payload", ResponsePayload.class),
CHAT_BUBBLE(5, "simple_response", ResponseChatBubble.class),
BASIC_CARD(6, "basic_card", ResponseBasicCard.class),
LIST_CARD(7, "list_card", ResponseListCard.class),
SUGGESTION_CHIPS(8, "suggestion_chips", ResponseSuggestionChips.class),
CAROUSEL_CARD(9, "carousel_card", ResponseCarouselCard.class),
LINK_OUT_CHIP(10, "link_out_chip", ResponseLinkOutChip.class);
private final int code;
private final String name;
private final Type type;
private MessageType(int code, String name, Type curClass) {
assert name != null;
assert curClass != null;
this.code = code;
this.name = name;
this.type = curClass;
}
/**
* @return Message integer code value
*/
public int getCode() {
return this.code;
}
/**
* @return Type name presentation
*/
public String getName() {
return name;
}
/**
* @return Related class {@link Type}
*/
public Type getType() {
return type;
}
private static Map<Integer,MessageType> typeByCode = new HashMap<>();
private static Map<String,MessageType> typeByName = new HashMap<>();
static {
for (MessageType type : values()) {
typeByCode.put(type.code, type);
typeByName.put(type.name.toLowerCase(), type);
}
}
public static MessageType fromCode(int code) {
return typeByCode.get(code);
}
public static MessageType fromName(String name) {
return typeByName.get(name != null ? name.toLowerCase() : null);
}
}
public enum Platform {
DEFAULT(null),
GOOGLE("google"),
FACEBOOK("facebook"),
SLACK("slack"),
TELEGRAM("telegram"),
KIK("kik"),
VIBER("viber"),
SKYPE("skype"),
LINE("line");
private final String name;
Platform(String name) {
this.name = name;
}
public String getName() {
return name;
}
private static Map<String,Platform> platformByName = new HashMap<>();
static {
for (Platform platform : values()) {
String platformName = platform.getName();
platformByName.put(platformName != null ? platformName.toLowerCase() : null, platform);
}
}
public static Platform fromName(String name) {
return platformByName.get(name != null ? name.toLowerCase() : null);
}
}
/**
* <a href="https://docs.api.ai/docs/query#section-text-response-message-object">Text response</a>
* message object
*/
public static class ResponseSpeech extends ResponseMessage {
@Expose
public List<String> speech;
public ResponseSpeech() {
super(MessageType.SPEECH);
}
/**
* Get agent's text replies.
*/
public List<String> getSpeech() {
return this.speech;
}
/**
* Set agent's text replies.
*/
public void setSpeech(List<String> speech) {
this.speech = speech;
}
/**
* Set agent's text replies.
*/
public void setSpeech(String... speech) {
setSpeech(Arrays.asList(speech));
}
}
/**
* <a href="https://docs.api.ai/docs/query#section-card-message-object">Card message</a> object
*/
public static class ResponseCard extends ResponseMessage {
@Expose
private String title;
@Expose
private String subtitle;
@Expose
private String imageUrl;
@Expose
private List<Button> buttons;
public ResponseCard() {
super(MessageType.CARD);
}
/** Get card title. */
public String getTitle() {
return this.title;
}
/** Set card title. */
public void setTitle(String title) {
this.title = title;
}
/** Get card subtitle. */
public String getSubtitle() {
return this.subtitle;
}
/** Set card subtitle. */
public void setSubtitle(String subtitle) {
this.subtitle = subtitle;
}
/** Get image url */
public String getImageUrl() {
return this.imageUrl;
}
/** Set image url */
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
/** Get list of objects corresponding to card buttons. */
public List<Button> getButtons() {
return this.buttons;
}
/** Set list of objects corresponding to card buttons. */
public void setButtons(List<Button> buttons) {
this.buttons = buttons;
}
/** Set sequence of objects corresponding to card buttons. */
public void setButtons(Button... buttons) {
setButtons(Arrays.asList(buttons));
}
/** Card button object */
public static class Button {
@Expose
private String text;
@Expose
private String postback;
public Button(String text, String postback) {
this.text = text;
this.postback = postback;
}
/** Set button text */
public void setText(String text) {
this.text = text;
}
/** Get button text */
public String getText() {
return this.text;
}
/** Set a text sent back to API.AI or a URL to open. */
public void setPostback(String postback) {
this.postback = postback;
}
/** Get a text sent back to API.AI or a URL to open. */
public String getPostback() {
return this.postback;
}
}
}
/** <a href="https://docs.api.ai/docs/query#section-quick-replies-message-object">Quick
* replies</a> message object */
public static class ResponseQuickReply extends ResponseMessage {
@Expose
private String title;
@Expose
private List<String> replies;
public ResponseQuickReply() {
super(MessageType.QUICK_REPLY);
}
/** Get list of text replies */
public List<String> getReplies() {
return this.replies;
}
/** Set list of text replies */
public void setReplies(List<String> replies) {
this.replies = replies;
}
/** Set sequence of text replies */
public void setReplies(String... replies) {
setReplies(Arrays.asList(replies));
}
/** Set quick replies title. Required for the Facebook Messenger, Kik, and Telegram one-click
* integrations. */
public void setTitle(String title) {
this.title = title;
}
/** Get quick replies title. Required for the Facebook Messenger, Kik, and Telegram one-click
* integrations. */
public String getTitle() {
return this.title;
}
}
/**
* <a href="https://docs.api.ai/docs/query#section-image-message-object">Image</a> message object
*/
public static class ResponseImage extends ResponseMessage {
@Expose
private String imageUrl;
public ResponseImage() {
super(MessageType.IMAGE);
}
/** Get image url */
public String getImageUrl() {
return this.imageUrl;
}
/** Set image url */
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
/**
* <a href="">Custom payload</a> message object that holds an object passed through without
* modification
*/
public static class ResponsePayload extends ResponseMessage {
@Expose
private JsonObject payload;
public ResponsePayload() {
super(MessageType.PAYLOAD);
}
/** Get custom defined JSON. */
public JsonObject getPayload() {
return this.payload;
}
/** Set custom defined JSON. */
public void setPayload(JsonObject payload) {
this.payload = payload;
}
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/model/Result.java
|
package ai.api.model;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2014 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import ai.api.util.StringUtils;
import ai.api.util.ParametersConverter;
public class Result implements Serializable {
private static final long serialVersionUID = 1L;
private static final String DATE_FORMAT_ERROR_MESSAGE = "'%s' parameter has value '%s' and can't be parsed as a Date or Time";
@SerializedName("action")
private String action;
@SerializedName("score")
private float score;
@SerializedName("source")
private String source;
/**
* This field will be deserialized as hashMap container with all parameters and it's values
*/
@SerializedName("parameters")
private HashMap<String, JsonElement> parameters;
/**
* Currently active contexts
*/
@SerializedName("contexts")
private List<AIOutputContext> contexts;
@SerializedName("metadata")
private Metadata metadata;
/**
* The query that was used to produce this result
*/
@SerializedName("resolvedQuery")
private String resolvedQuery;
/**
* Fulfillment of the response
*/
@SerializedName("fulfillment")
private Fulfillment fulfillment;
@SerializedName("actionIncomplete")
private boolean actionIncomplete;
public String getAction() {
if (action == null) {
return "";
}
return action;
}
public void setAction(final String action) {
this.action = action;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
public String getSource() {
return source;
}
public void setSource(final String source) {
this.source = source;
}
public Metadata getMetadata() {
return metadata;
}
public void setMetadata(final Metadata metadata) {
this.metadata = metadata;
}
public HashMap<String, JsonElement> getParameters() {
return parameters;
}
public String getStringParameter(final String name) {
return getStringParameter(name, "");
}
public String getStringParameter(final String name, final String defaultValue) {
if (parameters.containsKey(name)) {
final String parameterValue = parameters.get(name).getAsString();
return parameterValue;
}
return defaultValue;
}
public Date getDateParameter(final String name) throws IllegalArgumentException {
return getDateParameter(name, null);
}
public Date getDateParameter(final String name, final Date defaultValue) throws IllegalArgumentException {
if (parameters.containsKey(name)) {
final String parameterStringValue = parameters.get(name).getAsString();
if (StringUtils.isEmpty(parameterStringValue)) {
return defaultValue;
}
try {
return ParametersConverter.parseDate(parameterStringValue);
} catch (final ParseException pe) {
throw new IllegalArgumentException(String.format(DATE_FORMAT_ERROR_MESSAGE, name, parameterStringValue), pe);
}
}
return defaultValue;
}
public Date getDateTimeParameter(final String name) throws IllegalArgumentException {
return getDateTimeParameter(name, null);
}
public Date getDateTimeParameter(final String name, final Date defaultValue) throws IllegalArgumentException {
if (parameters.containsKey(name)) {
final String parameterStringValue = parameters.get(name).getAsString();
if (StringUtils.isEmpty(parameterStringValue)) {
return defaultValue;
}
try {
return ParametersConverter.parseDateTime(parameterStringValue);
} catch (final ParseException pe) {
throw new IllegalArgumentException(String.format(DATE_FORMAT_ERROR_MESSAGE, name, parameterStringValue), pe);
}
}
return defaultValue;
}
public Date getTimeParameter(final String name) throws IllegalArgumentException {
return getTimeParameter(name, null);
}
public Date getTimeParameter(final String name, final Date defaultValue) throws IllegalArgumentException {
if (parameters.containsKey(name)) {
final String parameterStringValue = parameters.get(name).getAsString();
if (StringUtils.isEmpty(parameterStringValue)) {
return defaultValue;
}
try {
return ParametersConverter.parseTime(parameterStringValue);
} catch (final ParseException pe) {
throw new IllegalArgumentException(String.format(DATE_FORMAT_ERROR_MESSAGE, name, parameterStringValue), pe);
}
}
return defaultValue;
}
public int getIntParameter(final String name) {
return getIntParameter(name, 0);
}
public int getIntParameter(final String name, final int defaultValue) {
if (parameters.containsKey(name)) {
final String parameterStringValue = parameters.get(name).getAsString();
if (StringUtils.isEmpty(parameterStringValue)) {
return defaultValue;
}
return ParametersConverter.parseInteger(parameterStringValue);
}
return defaultValue;
}
public float getFloatParameter(final String name) {
return getFloatParameter(name, 0);
}
public float getFloatParameter(final String name, final float defaultValue) {
if (parameters.containsKey(name)) {
final String parameterStringValue = parameters.get(name).getAsString();
if (StringUtils.isEmpty(parameterStringValue)) {
return defaultValue;
}
return ParametersConverter.parseFloat(parameterStringValue);
}
return defaultValue;
}
public JsonObject getComplexParameter(final String name, final JsonObject defaultValue) {
if (parameters.containsKey(name)) {
final JsonObject jsonObject = parameters.get(name).getAsJsonObject();
if (jsonObject == null) {
return defaultValue;
}
return jsonObject;
}
return defaultValue;
}
public JsonObject getComplexParameter(final String name) {
return getComplexParameter(name, null);
}
public List<AIOutputContext> getContexts() {
return contexts;
}
public AIOutputContext getContext(final String name) {
if (StringUtils.isEmpty(name)) {
throw new IllegalArgumentException("name argument must be not empty");
}
if (contexts == null) {
return null;
}
for (final AIOutputContext c : contexts) {
if (name.equalsIgnoreCase(c.getName())) {
return c;
}
}
return null;
}
/**
* The query that was used to produce this result
*/
public String getResolvedQuery() {
return resolvedQuery;
}
public void setResolvedQuery(final String resolvedQuery) {
this.resolvedQuery = resolvedQuery;
}
public Fulfillment getFulfillment() {
return fulfillment;
}
public void setFulfillment(final Fulfillment fulfillment) {
this.fulfillment = fulfillment;
}
public boolean isActionIncomplete() {
return actionIncomplete;
}
public void setActionIncomplete(final boolean actionIncomplete) {
this.actionIncomplete = actionIncomplete;
}
void trimParameters() {
if (parameters != null) {
final List<String> parametersToTrim = new LinkedList<String>();
for (final String key : parameters.keySet()) {
final JsonElement jsonElement = parameters.get(key);
if (jsonElement != null && jsonElement.isJsonPrimitive()) {
if (((JsonPrimitive) jsonElement).isString() && StringUtils.isEmpty(jsonElement.getAsString())) {
parametersToTrim.add(key);
}
}
}
for (final String key : parametersToTrim) {
parameters.remove(key);
}
}
}
@Override
public String toString() {
return String.format("Result {action='%s', resolvedQuery='%s'}",
action,
resolvedQuery);
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/model/Status.java
|
package ai.api.model;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2014 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
public class Status implements Serializable {
private static final long serialVersionUID = 1L;
private static final Map<Integer, String> errorDescriptions = new HashMap<>();
private static final Map<Integer, String> errorTypes = new HashMap<>();
{
errorDescriptions.put(400,"Some required parameter is missing or has wrong value. Details will be in the errorDetails field.");
errorTypes.put(400,"bad_request");
errorDescriptions.put(401,"Authorization failed. Please check your access keys.");
errorTypes.put(401,"unauthorized");
errorDescriptions.put(404,"Uri is not found or some resource with provided id is not found.");
errorTypes.put(404,"not_found");
errorDescriptions.put(405,"Attempting to use POST with a GET-only endpoint, or vice-versa.");
errorTypes.put(405,"not_allowed");
errorDescriptions.put(406,"Uploaded files have some problems with it.");
errorTypes.put(406,"not_acceptable");
errorDescriptions.put(409,"The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request.");
errorTypes.put(409,"conflict");
}
public static Status fromResponseCode(final int responseCode) {
final Status status = new Status();
status.setCode(responseCode);
if (errorTypes.containsKey(responseCode)) {
status.setErrorType(errorTypes.get(responseCode));
}
if (errorDescriptions.containsKey(responseCode)) {
status.setErrorDetails(errorDescriptions.get(responseCode));
}
return status;
}
/**
* Response Status Code.
* Possible values
* <ul>
* <li><b>400</b> bad_request - Some required parameter is missing or has wrong value. Details will be in the errorDetails field.</li>
* <li><b>401</b> unauthorized - Internal authorization failed. It might mean missing or wrong credentials.</li>
* <li><b>404</b> not_found - Returned if uri is not found or some resource with provided id is not found.</li>
* <li><b>405</b> not_allowed - Attempting to use POST with a GET-only endpoint, or vice-versa.</li>
* <li><b>406</b> not_acceptable - Can be returned if uploaded files have some problems with it.</li>
* <li><b>200</b> deprecated - Can be used to indicate that some resource is deprecated and will be removed in the future.</li>
* <li><b>409</b> conflict - The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request.</li>
* </ul>
*/
@SerializedName("code")
private Integer code;
/**
* Error type.
* Possible values:
* <ul>
* <li><b>bad_request</b> - Some required parameter is missing or has wrong value. Details will be in the errorDetails field.</li>
* <li><b>unauthorized</b> - Internal authorization failed. It might mean missing or wrong credentials.</li>
* <li><b>not_found</b> - Returned if uri is not found or some resource with provided id is not found.</li>
* <li><b>not_allowed</b> - Attempting to use POST with a GET-only endpoint, or vice-versa.</li>
* <li><b>not_acceptable</b> - Can be returned if uploaded files have some problems with it.</li>
* <li><b>deprecated</b> - Can be used to indicate that some resource is deprecated and will be removed in the future.</li>
* <li><b>conflict</b> - The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request.</li>
* </ul>
*/
@SerializedName("errorType")
private String errorType;
/**
* Human readable error description.
*/
@SerializedName("errorDetails")
private String errorDetails;
/**
* Error unique ID. Use it in the requests to API.AI support.
*/
@SerializedName("errorID")
private String errorID;
/**
* Response Status Code.
* Possible values:
* <ul>
* <li><b>400</b> bad_request - Some required parameter is missing or has wrong value. Details will be in the errorDetails field.</li>
* <li><b>401</b> unauthorized - Internal authorization failed. It might mean missing or wrong credentials.</li>
* <li><b>404</b> not_found - Returned if uri is not found or some resource with provided id is not found.</li>
* <li><b>405</b> not_allowed - Attempting to use POST with a GET-only endpoint, or vice-versa.</li>
* <li><b>406</b> not_acceptable - Can be returned if uploaded files have some problems with it.</li>
* <li><b>200</b> deprecated - Can be used to indicate that some resource is deprecated and will be removed in the future.</li>
* <li><b>409</b> conflict - The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request.</li>
* </ul>
*/
public Integer getCode() {
return code;
}
public void setCode(final Integer code) {
this.code = code;
}
public String getErrorType() {
return errorType;
}
public void setErrorType(final String errorType) {
this.errorType = errorType;
}
public String getErrorDetails() {
if (code != null && errorDescriptions.containsKey(code)) {
return errorDescriptions.get(code);
}
return errorDetails;
}
public void setErrorDetails(final String errorDetails) {
this.errorDetails = errorDetails;
}
public String getErrorID() {
return errorID;
}
public void setErrorID(final String errorID) {
this.errorID = errorID;
}
@Override
public String toString() {
return String.format("Status{code=%d, errorType='%s', errorDetails='%s'}",
code,
errorType,
errorDetails);
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/util/IOUtils.java
|
package ai.api.util;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2017 by Speaktoit, Inc. (https://www.speaktoit.com) https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
***********************************************************************************************************************/
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.charset.Charset;
/**
* Small subset of IO helping functions
*/
public class IOUtils {
private static final int DEFAULT_BUFFER_SIZE = 4096;
private static final String DEFAULT_CHARSET = "UTF-8";
/**
* Write string to byte stream
*
* @param data Source string
* @param outputStream Output stream
* @param charset Convert string to bytes according to given {@link Charset}
* @throws IOException
*/
public static void writeAll(String data, OutputStream outputStream, Charset charset)
throws IOException {
writeAll(data, outputStream, charset.name());
}
/**
* Write string to byte stream
*
* @param data Source string
* @param outputStream Output stream
* @param charset Convert string to bytes according to given
* @throws IOException
*/
public static void writeAll(String data, OutputStream outputStream, String charset)
throws IOException {
if ((data != null) && (data.length() > 0)) {
outputStream.write(data.getBytes(charset));
}
}
/**
* Write string to byte stream
*
* @param data Source string
* @param outputStream Output stream
* @throws IOException
*/
public static void writeAll(String data, OutputStream outputStream) throws IOException {
writeAll(data, outputStream, DEFAULT_CHARSET);
}
/**
* Read all stream byte data into {@link String}
*
* @param inputStream Source stream
* @param charset Convert bytes to chars according to given {@link Charset}
* @return Empty {@link String} if there was no data in stream
* @throws IOException
*/
public static String readAll(InputStream inputStream, Charset charset) throws IOException {
return readAll(inputStream, charset.name());
}
/**
* Read all stream byte data into {@link String}
*
* @param inputStream Source stream
* @param charset Convert bytes to chars according to given
* @return Empty {@link String} if there was no data in stream
* @throws IOException
*/
public static String readAll(InputStream inputStream, String charset) throws IOException {
try (InputStreamReader streamReader = new InputStreamReader(inputStream, charset)) {
return readAll(streamReader);
}
}
/**
* Read all stream byte data into {@link String}
*
* @param inputStream Source stream
* @return Empty {@link String} if there was no data in stream
* @throws IOException
*/
public static String readAll(InputStream inputStream) throws IOException {
return readAll(inputStream, DEFAULT_CHARSET);
}
/**
* Read all chars into String
*
* @param streamReader Input stream reader
* @return Empty {@link String} if there was no data in stream
* @throws IOException
*/
public static String readAll(InputStreamReader streamReader) throws IOException {
StringWriter result = new StringWriter();
copy(streamReader, result);
return result.toString();
}
private static long copy(Reader reader, Writer writer) throws IOException {
return copy(reader, writer, new char[DEFAULT_BUFFER_SIZE]);
}
private static long copy(Reader reader, Writer writer, char[] buffer) throws IOException {
assert buffer != null;
assert buffer.length > 0;
long result = 0;
int read = reader.read(buffer);
while (read > 0) {
writer.write(buffer, 0, read);
result += read;
read = reader.read(buffer);
}
return result;
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/util/ParametersConverter.java
|
package ai.api.util;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2016 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* Helper to extract possible response parameters values
*/
public final class ParametersConverter {
public static final String PROTOCOL_DATE_FORMAT = "yyyy-MM-dd";
public static final String PROTOCOL_DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZ";
public static final String PROTOCOL_TIME_FORMAT = "HH:mm:ss";
private static final DateFormat DATE_FORMAT = new SimpleDateFormat(PROTOCOL_DATE_FORMAT, Locale.US);
private static final DateFormat DATE_TIME_FORMAT = new SimpleDateFormat(PROTOCOL_DATE_TIME_FORMAT, Locale.US);
private static final DateFormat TIME_FORMAT = new SimpleDateFormat(PROTOCOL_TIME_FORMAT, Locale.US);
/**
* Constructor is hidden to make the class a static used only
*/
private ParametersConverter() {
}
/**
* @param parameter Cannot be <code>null</code>
* @return Never <code>null</code>
* @throws ParseException
*/
public static Date parseDateTime(final String parameter) throws ParseException {
if (parameter == null) {
throw new IllegalArgumentException("Parameter must not be null");
}
return DATE_TIME_FORMAT.parse(parameter);
}
/**
* @param parameter Cannot be <code>null</code>
* @return Never <code>null</code>
* @throws ParseException
*/
public static Date parseDate(final String parameter) throws ParseException {
if (parameter == null) {
throw new IllegalArgumentException("Parameter must not be null");
}
return DATE_FORMAT.parse(parameter);
}
/**
* @param parameter Cannot be <code>null</code>
* @return Never <code>null</code>
* @throws ParseException
*/
public static Date parseTime(final String parameter) throws ParseException {
if (parameter == null) {
throw new IllegalArgumentException("Parameter must not be null");
}
final Calendar timeParameter = Calendar.getInstance();
timeParameter.setTime(TIME_FORMAT.parse(parameter));
final Calendar taskDueDate = Calendar.getInstance();
taskDueDate.set(Calendar.HOUR_OF_DAY, timeParameter.get(Calendar.HOUR_OF_DAY));
taskDueDate.set(Calendar.MINUTE, timeParameter.get(Calendar.MINUTE));
taskDueDate.set(Calendar.SECOND, timeParameter.get(Calendar.SECOND));
return taskDueDate.getTime();
}
/**
*
* @param parameter Cannot be <code>null</code>
* @return Never <code>null</code>
* @throws ParseException
*/
public static PartialDate parsePartialDate(final String parameter) throws ParseException {
if (parameter == null) {
throw new IllegalArgumentException("Parameter must not be empty");
}
if (parameter.length() == 0) {
throw new ParseException("Parameter must not be empty", 0);
}
if (parameter.contains("u")) {
// if date contains unknown parts
final String[] parts = parameter.split("-");
if (parts.length != 3) {
throw new ParseException(String.format("Partial date must have 3 parts, but have %s: %s", parts.length, parameter), 0);
}
// check each part for unknown
// each part must contains all digits or all 'u' without mixing
final Integer year = parsePart(parts[0]);
final Integer month = parsePart(parts[1]);
final Integer day = parsePart(parts[2]);
final PartialDate result = new PartialDate();
result.set(Calendar.YEAR, year);
result.set(Calendar.MONTH, month);
result.set(Calendar.DATE, day);
return result;
} else {
// parse as normal date
return new PartialDate(DATE_FORMAT.parse(parameter));
}
}
/**
*
* @param parameter Cannot be <code>null</code>
* @return Never <code>null</code>
* @throws NumberFormatException
*/
public static int parseInteger(final String parameter) throws NumberFormatException {
return Integer.parseInt(parameter);
}
/**
*
* @param parameter Cannot be <code>null</code>
* @return Never <code>null</code>
*/
public static float parseFloat(final String parameter) {
if (parameter == null) {
throw new IllegalArgumentException("Parameter must not be empty");
}
return Float.parseFloat(parameter);
}
/**
*
* @param part Cannot be <code>null</code>
* @return Never <code>null</code>
*/
private static Integer parsePart(final String part) {
if (part == null) {
throw new IllegalArgumentException("part");
}
if (part.indexOf('u') >= 0) {
return PartialDate.UNSPECIFIED_VALUE;
} else {
return Integer.parseInt(part);
}
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/util/PartialDate.java
|
package ai.api.util;
/***********************************************************************************************************************
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
* *********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
***********************************************************************************************************************/
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.Set;
/**
Class representing date with some unknown field values. Format according to http://www.loc.gov/standards/datetime/pre-submission.html
*/
public class PartialDate {
public static final Integer UNSPECIFIED_VALUE = null;
private static final String UNSPECIFIED_YEAR = "uuuu";
private static final String UNSPECIFIED_MONTH = "uu";
private static final String UNSPECIFIED_DATE = "uu";
private static final String UNSPECIFIED_HOUR = "uu";
private static final String UNSPECIFIED_MINUTE = "uu";
private final Calendar c;
private final Set<Integer> unspecifiedFields = new HashSet<>();
public PartialDate() {
c = Calendar.getInstance();
}
public PartialDate(final Calendar calendar) {
this.c = calendar;
}
public PartialDate(final Date date) {
this();
c.setTime(date);
}
public void set(final int field, final Integer value) {
if (value == UNSPECIFIED_VALUE) {
if (field == Calendar.YEAR) {
unspecifiedFields.add(Calendar.YEAR);
} else if (field == Calendar.MONTH) {
unspecifiedFields.add(Calendar.MONTH);
} else if (field >= Calendar.WEEK_OF_YEAR && field <= Calendar.DAY_OF_WEEK_IN_MONTH) {
unspecifiedFields.add(Calendar.DATE);
} else if (field >= Calendar.HOUR && field <= Calendar.HOUR_OF_DAY) {
unspecifiedFields.add(Calendar.HOUR_OF_DAY);
} else if (field == Calendar.MINUTE) {
unspecifiedFields.add(Calendar.MINUTE);
}
// do nothing with other fields
} else {
unspecifiedFields.remove(field);
c.set(field, value);
}
}
public Integer get(final int field) {
if (field == Calendar.YEAR) {
if (!unspecifiedFields.contains(Calendar.YEAR)) {
return c.get(field);
}
return UNSPECIFIED_VALUE;
} else if (field == Calendar.MONTH) {
if (!unspecifiedFields.contains(Calendar.MONTH)) {
return c.get(field);
}
return UNSPECIFIED_VALUE;
} else if (field >= Calendar.WEEK_OF_YEAR && field <= Calendar.DAY_OF_WEEK_IN_MONTH) {
if (!unspecifiedFields.contains(Calendar.DATE)) {
return c.get(field);
}
return UNSPECIFIED_VALUE;
} else if (field >= Calendar.HOUR && field <= Calendar.HOUR_OF_DAY) {
if (!unspecifiedFields.contains(Calendar.HOUR_OF_DAY)) {
return c.get(field);
}
return UNSPECIFIED_VALUE;
} else if (field == Calendar.MINUTE) {
if (!unspecifiedFields.contains(Calendar.MINUTE)) {
return c.get(Calendar.MINUTE);
}
return UNSPECIFIED_VALUE;
} else {
return c.get(field);
}
//return UNSPECIFIED_VALUE;
}
private String getFieldAsString(final int field) {
if (field == Calendar.YEAR) {
if (unspecifiedFields.contains(Calendar.YEAR)) {
return UNSPECIFIED_YEAR;
} else {
return String.format("%4d", c.get(field));
}
} else if (field == Calendar.MONTH) {
if (unspecifiedFields.contains(Calendar.MONTH)) {
return UNSPECIFIED_MONTH;
} else {
return String.format("%02d", c.get(field));
}
} else if (field >= Calendar.WEEK_OF_YEAR && field <= Calendar.DAY_OF_WEEK_IN_MONTH) {
if (unspecifiedFields.contains(Calendar.DATE)) {
return UNSPECIFIED_DATE;
} else {
return String.format("%02d", c.get(field));
}
} else if (field >= Calendar.HOUR && field <= Calendar.HOUR_OF_DAY) {
if (unspecifiedFields.contains(Calendar.HOUR_OF_DAY)) {
return UNSPECIFIED_HOUR;
} else {
return String.format("%02d", c.get(field));
}
} else if (field == Calendar.MINUTE) {
if (unspecifiedFields.contains(Calendar.MINUTE)) {
return UNSPECIFIED_MINUTE;
} else {
return String.format("%02d", c.get(field));
}
} else {
return String.format("%s", c.get(field));
}
}
@Override
public String toString() {
return String.format("%s-%s-%s",
getFieldAsString(Calendar.YEAR),
getFieldAsString(Calendar.MONTH),
getFieldAsString(Calendar.DATE));
}
}
|
0
|
java-sources/ai/api/libai/1.6.12/ai/api
|
java-sources/ai/api/libai/1.6.12/ai/api/util/StringUtils.java
|
package ai.api.util;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2016 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
/**
* A small set of string utils functions
*/
public class StringUtils {
/**
* Checks if a CharSequence is null or has no characters.
* @param value the CharSequence to check
* @return {@code true} if the CharSequence is null or null
*/
public static boolean isEmpty(final CharSequence value) {
return (value == null) || (value.length() == 0);
}
}
|
0
|
java-sources/ai/api/libai/speech/libai-speech-gcp/1.6.12/ai/api/speech
|
java-sources/ai/api/libai/speech/libai-speech-gcp/1.6.12/ai/api/speech/gcp/GcpAIConfiguration.java
|
package ai.api.speech.gcp;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2016 by Speaktoit, Inc. (https://www.speaktoit.com) https://www.api.ai
*
* *********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
***********************************************************************************************************************/
import java.util.Arrays;
import java.util.List;
import com.google.cloud.speech.v1.RecognitionConfig;
import com.google.cloud.speech.v1.RecognitionConfig.AudioEncoding;
import ai.api.AIConfiguration;
/**
* Configuration for {@link GcpAIDataService}
*/
public class GcpAIConfiguration extends AIConfiguration {
private static final int DEFAULT_SAMPLING_RATE = 16000;
private String speechApiHost = "speech.googleapis.com";
private int speechApiPort = 443;
private List<String> authScope = Arrays.asList("https://www.googleapis.com/auth/cloud-platform");
private RecognitionConfig recognitionConfig = RecognitionConfig.newBuilder()
.setEncoding(AudioEncoding.LINEAR16)
.setSampleRateHertz(DEFAULT_SAMPLING_RATE)
.setLanguageCode(getLanguage())
.build();
/**
* Create new configuration and initialize client access token
* @param clientAccessToken <a href="https://docs.api.ai/docs/authentication#obtaining-access-tokens">
* Client access token</a>
*/
public GcpAIConfiguration(final String clientAccessToken) {
super(clientAccessToken);
}
/**
* Create new configuration and initialize client access token
* @param clientAccessToken <a href="https://docs.api.ai/docs/authentication#obtaining-access-tokens">
* Client access token</a>
* @param language Supported language
*/
public GcpAIConfiguration(final String clientAccessToken, final SupportedLanguages language) {
super(clientAccessToken, language);
}
/**
* @see AIConfiguration#clone()
*/
@Override
public GcpAIConfiguration clone() {
return (GcpAIConfiguration)super.clone();
}
/**
* Get URI for speech API service
*/
public final String getSpeechApiHost() {
return speechApiHost;
}
/**
* Set URI for speech API service
*/
public final void setSpeechApiHost(String speechApiHost) {
this.speechApiHost = speechApiHost;
}
/**
* Get port number for speech API service
*/
public final int getSpeechApiPort() {
return speechApiPort;
}
/**
* Set port number for speech API service
*/
public final void setSpeechApiPort(int speechApiPort) {
this.speechApiPort = speechApiPort;
}
public final List<String> getAuthScope() {
return authScope;
}
public final void setAuthScope(List<String> authScope) {
this.authScope = authScope;
}
/**
* Get recognition configuration
* @return <code>null</code> if recognition configuration is undefined
*/
public final RecognitionConfig getRecognitionConfig() {
return recognitionConfig;
}
/**
* Set recognition configuration
*/
public final void setRecognitionConfig(RecognitionConfig recognitionConfig) {
this.recognitionConfig = recognitionConfig;
}
}
|
0
|
java-sources/ai/api/libai/speech/libai-speech-gcp/1.6.12/ai/api/speech
|
java-sources/ai/api/libai/speech/libai-speech-gcp/1.6.12/ai/api/speech/gcp/GcpAIDataService.java
|
package ai.api.speech.gcp;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2016 by Speaktoit, Inc. (https://www.speaktoit.com) https://www.api.ai
*
* *********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
***********************************************************************************************************************/
import java.io.IOException;
import java.io.InputStream;
import com.google.cloud.speech.spi.v1.SpeechClient;
import com.google.cloud.speech.v1.RecognitionAudio;
import com.google.cloud.speech.v1.RecognizeResponse;
import com.google.protobuf.ByteString;
import ai.api.AIDataService;
import ai.api.AIServiceContext;
import ai.api.AIServiceException;
import ai.api.RequestExtras;
import ai.api.model.AIRequest;
import ai.api.model.AIResponse;
import io.grpc.StatusRuntimeException;
/**
* AIDataService with Google Speech API support
*/
public class GcpAIDataService extends AIDataService {
private final GcpAIConfiguration config;
/**
* Create new instance of AI data service
* @param config Service configuration
*/
public GcpAIDataService(GcpAIConfiguration config) {
super(config);
this.config = config.clone();
}
/**
* Create new instance of AI data service
* @param config Service configuration
* @param serviceContext Default service context
*/
public GcpAIDataService(GcpAIConfiguration config, AIServiceContext serviceContext) {
super(config, serviceContext);
this.config = config.clone();
}
/**
* @see AIDataService#voiceRequest(InputStream, RequestExtras, AIServiceContext)
*/
@Override
public AIResponse voiceRequest(InputStream voiceStream, RequestExtras requestExtras,
AIServiceContext serviceContext) throws AIServiceException {
RecognizeResponse response;
try {
SpeechClient speechClient = SpeechClient.create();
RecognitionAudio recognitionAudio = createRecognitionAudio(voiceStream);
response = speechClient.recognize(config.getRecognitionConfig(), recognitionAudio);
} catch (IOException | StatusRuntimeException e) {
throw new AIServiceException("Failed to recognize speech", e);
}
if ((response.getResultsCount() == 0) || (response.getResults(0).getAlternativesCount() == 0)) {
throw new AIServiceException("No speech");
}
String transcript = response.getResults(0).getAlternatives(0).getTranscript();
AIRequest request = new AIRequest(transcript);
return request(request, requestExtras, serviceContext);
}
private RecognitionAudio createRecognitionAudio(InputStream voiceStream) throws IOException {
return RecognitionAudio.newBuilder().setContent(ByteString.readFrom(voiceStream)).build();
}
}
|
0
|
java-sources/ai/api/libai/web/libai-web-servlet/1.6.12/ai/api
|
java-sources/ai/api/libai/web/libai-web-servlet/1.6.12/ai/api/web/AIServiceServlet.java
|
package ai.api.web;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2017 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import ai.api.AIConfiguration;
import ai.api.AIDataService;
import ai.api.AIServiceContext;
import ai.api.AIServiceContextBuilder;
import ai.api.AIServiceException;
import ai.api.model.AIRequest;
import ai.api.model.AIResponse;
/**
* Basic AI service servlet.
*
* Must be initialized with {@link AIServiceServlet#PARAM_API_AI_KEY} parameter.
* Set your <a href="https://docs.api.ai/docs/authentication#obtaining-access-tokens">
* api.ai access token</a> as a value.
*/
public abstract class AIServiceServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Api.ai access token parameter name
*/
public static final String PARAM_API_AI_KEY = "apiaiKey";
private AIDataService aiDataService;
/**
* @see HttpServlet#init(ServletConfig config)
*/
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
AIConfiguration aiConfig = new AIConfiguration(config.getInitParameter(PARAM_API_AI_KEY));
aiDataService = new AIDataService(aiConfig);
}
/**
* Perform request to AI data service
* @param aiRequest Request object. Cannot be <code>null</code>.
* @param serviceContext Service context. If <code>null</code> then default context will be used.
* @return Response object
* @throws AIServiceException Thrown on server access error
*/
protected final AIResponse request(AIRequest aiRequest, AIServiceContext serviceContext)
throws AIServiceException {
return aiDataService.request(aiRequest, serviceContext);
}
/**
* Perform request to AI data service
* @param query Request plain text string. Cannot be <code>null</code>.
* @param serviceContext Service context. If <code>null</code> then default context will be used.
* @return Response object
* @throws AIServiceException Thrown on server access error
*/
protected final AIResponse request(String query, AIServiceContext serviceContext)
throws AIServiceException {
return request(new AIRequest(query), serviceContext);
}
/**
* Perform request to AI data service
* @param aiRequest Request object. Cannot be <code>null</code>.
* @param session Session object. If <code>null</code> then default context will be used.
* @return Response object
* @throws AIServiceException Thrown on server access error
*/
protected final AIResponse request(AIRequest aiRequest, HttpSession session)
throws AIServiceException {
return request(aiRequest,
(session != null) ? AIServiceContextBuilder.buildFromSessionId(session.getId()) : null);
}
/**
* Perform request to AI data service
* @param query Request plain text string. Cannot be <code>null</code>.
* @param session Session object. If <code>null</code> then default context will be used.
* @return Response object
* @throws AIServiceException Thrown on server access error
*/
protected final AIResponse request(String query, HttpSession session) throws AIServiceException {
return request(new AIRequest(query),
(session != null) ? AIServiceContextBuilder.buildFromSessionId(session.getId()) : null);
}
/**
* Perform request to AI data service
* @param aiRequest Request object. Cannot be <code>null</code>.
* @param sessionId Session string id. If <code>null</code> then default context will be used.
* @return Response object
* @throws AIServiceException Thrown on server access error
*/
protected final AIResponse request(AIRequest aiRequest, String sessionId)
throws AIServiceException {
return request(aiRequest,
(sessionId != null) ? AIServiceContextBuilder.buildFromSessionId(sessionId) : null);
}
/**
* Perform request to AI data service
* @param query Request plain text string. Cannot be <code>null</code>.
* @param sessionId Session string id. If <code>null</code> then default context will be used.
* @return Response object
* @throws AIServiceException Thrown on server access error
*/
protected final AIResponse request(String query, String sessionId) throws AIServiceException {
return request(new AIRequest(query),
(sessionId != null) ? AIServiceContextBuilder.buildFromSessionId(sessionId) : null);
}
}
|
0
|
java-sources/ai/api/libai/web/libai-web-servlet/1.6.12/ai/api
|
java-sources/ai/api/libai/web/libai-web-servlet/1.6.12/ai/api/web/AIWebhookServlet.java
|
package ai.api.web;
/***********************************************************************************************************************
*
* API.AI Java SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2017 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import ai.api.GsonFactory;
import ai.api.model.AIResponse;
import ai.api.model.Fulfillment;
/**
* Basic web-hook servlet
*/
public abstract class AIWebhookServlet extends HttpServlet {
private static final String RESPONSE_CONTENT_TYPE = "application/json";
private static final String RESPONSE_CHARACTER_ENCODING = "utf-8";
private static final long serialVersionUID = 1L;
private final Gson gson = GsonFactory.getDefaultFactory().getGson();
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Fulfillment output = new Fulfillment();
doWebhook(gson.fromJson(request.getReader(), AIWebhookRequest.class), output);
response.setCharacterEncoding(RESPONSE_CHARACTER_ENCODING);
response.setContentType(RESPONSE_CONTENT_TYPE);
gson.toJson(output, response.getWriter());
}
/**
* Web-hook processing method.
* @param input Received request object
* @param output Response object. Should be filled in the method.
*/
protected abstract void doWebhook(AIWebhookRequest input, Fulfillment output);
/**
* Web-hook request model class
*/
protected static class AIWebhookRequest extends AIResponse {
private static final long serialVersionUID = 1L;
private OriginalRequest originalRequest;
/**
* Get original request object
* @return <code>null</code> if original request undefined in
* request object
*/
public OriginalRequest getOriginalRequest() {
return originalRequest;
}
}
/**
* Original request model class
*/
protected static class OriginalRequest implements Serializable {
private static final long serialVersionUID = 1L;
private String source;
private Map<String, ?> data;
/**
* Get source description string
* @return <code>null</code> if source isn't defined in a request
*/
public String getSource() {
return source;
}
/**
* Get data map
* @return <code>null</code> if data isn't defined in a request
*/
public Map<String, ?> getData() {
return data;
}
}
}
|
0
|
java-sources/ai/api/sdk/2.0.7/ai
|
java-sources/ai/api/sdk/2.0.7/ai/api/AIListener.java
|
package ai.api;
/***********************************************************************************************************************
*
* API.AI Android SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import ai.api.android.AIService;
import ai.api.model.AIError;
import ai.api.model.AIResponse;
/**
* Listener interface for working with API.AI service. Create implementation of it and use with {@link AIService AIService}
*/
public interface AIListener {
/**
* Event fires when entire process finished successfully, and returns result object
*
* @param result the result object, contains server answer
*/
void onResult(AIResponse result);
/**
* Event fires if something going wrong while recognition or access to the AI server
*
* @param error the error description object
*/
void onError(AIError error);
/**
* Event fires every time sound level changed. Use it to create visual feedback. There is no guarantee that this method will
* be called.
*
* @param level the new RMS dB value
*/
void onAudioLevel(float level);
/**
* Event fires when recognition engine start listening
*/
void onListeningStarted();
/**
* Event fires when recognition engine cancel listening
*/
void onListeningCanceled();
/**
* Event fires when recognition engine finish listening
*/
void onListeningFinished();
}
|
0
|
java-sources/ai/api/sdk/2.0.7/ai
|
java-sources/ai/api/sdk/2.0.7/ai/api/DefaultAIListener.java
|
package ai.api;
/***********************************************************************************************************************
*
* API.AI Android SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
/**
* Use this class instead of AIListener if you don't want to process all recognition events. Only onResult and onError required.
*/
public abstract class DefaultAIListener implements AIListener {
@Override
public void onAudioLevel(final float level) {
}
@Override
public void onListeningStarted() {
}
@Override
public void onListeningFinished() {
}
}
|
0
|
java-sources/ai/api/sdk/2.0.7/ai
|
java-sources/ai/api/sdk/2.0.7/ai/api/PartialResultsListener.java
|
package ai.api;
/***********************************************************************************************************************
*
* API.AI Android SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import java.util.List;
public interface PartialResultsListener {
void onPartialResults(final List<String> partialResults);
}
|
0
|
java-sources/ai/api/sdk/2.0.7/ai/api
|
java-sources/ai/api/sdk/2.0.7/ai/api/android/AIConfiguration.java
|
package ai.api.android;
/***********************************************************************************************************************
*
* API.AI Android SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
* *********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import android.content.res.AssetFileDescriptor;
import android.text.TextUtils;
import java.net.Proxy;
public class AIConfiguration extends ai.api.AIConfiguration {
public enum RecognitionEngine {
/**
* Google Speech Recognition integrated into Android OS
*
* @deprecated Use System instead
*/
@Deprecated
Google,
/**
* Default system recognition
*/
System,
/**
* Speaktoit recognition engine
*
* @deprecated Use System instead
* will be support until 01.02.2017
*/
@Deprecated
Speaktoit
}
private final RecognitionEngine recognitionEngine;
/**
* Speaktoit recognition start sound resouce descriptor
*/
private AssetFileDescriptor recognizerStartSound;
/**
* Speaktoit recognition stop sound resouce descriptor
*/
private AssetFileDescriptor recognizerStopSound;
/**
* Speaktoit recognition cancel sound resource descriptor
*/
private AssetFileDescriptor recognizerCancelSound;
private boolean voiceActivityDetectionEnabled = true;
private boolean normalizeInputSound = false;
public AIConfiguration(final String clientAccessToken, final SupportedLanguages language, final RecognitionEngine recognitionEngine) {
super(clientAccessToken, language);
this.recognitionEngine = recognitionEngine;
if (recognitionEngine == RecognitionEngine.Speaktoit
&& language == SupportedLanguages.Korean) {
throw new UnsupportedOperationException("Only System recognition supported for Korean language");
}
}
public RecognitionEngine getRecognitionEngine() {
return recognitionEngine;
}
public boolean isVoiceActivityDetectionEnabled() {
return voiceActivityDetectionEnabled;
}
/**
* With setting this field to false you can disable voice activity detection for Speaktoit recognition.
* This option does not affect System recognition.
* @param voiceActivityDetectionEnabled
*/
public void setVoiceActivityDetectionEnabled(final boolean voiceActivityDetectionEnabled) {
this.voiceActivityDetectionEnabled = voiceActivityDetectionEnabled;
}
/**
* With setting this field to true you can enable sound amplification if it's too quiet. This option improves recognition quality on some devices.
* This option does not affect System recognition.
* @param normalizeInputSound
*/
public void setNormalizeInputSound(final boolean normalizeInputSound) {
this.normalizeInputSound = normalizeInputSound;
}
public boolean isNormalizeInputSound() {
return normalizeInputSound;
}
public AssetFileDescriptor getRecognizerStartSound() {
return recognizerStartSound;
}
public void setRecognizerStartSound(final AssetFileDescriptor recognizerStartSound) {
this.recognizerStartSound = recognizerStartSound;
}
public AssetFileDescriptor getRecognizerStopSound() {
return recognizerStopSound;
}
public void setRecognizerStopSound(final AssetFileDescriptor recognizerStopSound) {
this.recognizerStopSound = recognizerStopSound;
}
public AssetFileDescriptor getRecognizerCancelSound() {
return recognizerCancelSound;
}
public void setRecognizerCancelSound(final AssetFileDescriptor recognizerCancelSound) {
this.recognizerCancelSound = recognizerCancelSound;
}
}
|
0
|
java-sources/ai/api/sdk/2.0.7/ai/api
|
java-sources/ai/api/sdk/2.0.7/ai/api/android/AIDataService.java
|
package ai.api.android;
/***********************************************************************************************************************
*
* API.AI Android SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
* *********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import android.content.Context;
import android.support.annotation.NonNull;
import com.google.gson.Gson;
import java.util.TimeZone;
import ai.api.AIServiceContext;
/**
* Do simple requests to the AI Service
*/
public class AIDataService extends ai.api.AIDataService {
public static final String TAG = AIDataService.class.getName();
@NonNull
private final Context context;
@NonNull
private final AIConfiguration config;
@NonNull
private final Gson gson = GsonFactory.getGson();
public AIDataService(@NonNull final Context context, @NonNull final AIConfiguration config) {
super(config, new AIAndroidServiceContext(context));
this.context = context;
this.config = config;
}
private static class AIAndroidServiceContext implements AIServiceContext {
private final String sessionId;
public AIAndroidServiceContext(final Context context) {
sessionId = SessionIdStorage.getSessionId(context);
}
public String getSessionId() {
return sessionId;
}
public TimeZone getTimeZone() { return TimeZone.getDefault(); }
}
}
|
0
|
java-sources/ai/api/sdk/2.0.7/ai/api
|
java-sources/ai/api/sdk/2.0.7/ai/api/android/AIService.java
|
package ai.api.android;
/***********************************************************************************************************************
*
* API.AI Android SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import android.Manifest;
import android.content.Context;
import java.util.Collection;
import java.util.List;
import ai.api.AIListener;
import ai.api.AIServiceException;
import ai.api.RequestExtras;
import ai.api.model.AIContext;
import ai.api.model.AIError;
import ai.api.model.AIRequest;
import ai.api.model.AIResponse;
import ai.api.model.Entity;
import ai.api.services.GoogleRecognitionServiceImpl;
import ai.api.services.SpeaktoitRecognitionServiceImpl;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
/**
* Main SDK class for working with API.AI service.
*/
public abstract class AIService {
private static final String TAG = AIService.class.getName();
protected final AIConfiguration config;
protected final Context context;
protected final AIDataService aiDataService;
private AIListener listener;
/**
* Use this method to get ready to work instance
* @param context
* @param config
* @return instance of AIService implementation
*/
public static AIService getService(final Context context, final AIConfiguration config) {
if (config.getRecognitionEngine() == AIConfiguration.RecognitionEngine.Google) {
return new GoogleRecognitionServiceImpl(context, config);
}
if (config.getRecognitionEngine() == AIConfiguration.RecognitionEngine.System) {
return new GoogleRecognitionServiceImpl(context, config);
}
else if (config.getRecognitionEngine() == AIConfiguration.RecognitionEngine.Speaktoit) {
return new SpeaktoitRecognitionServiceImpl(context, config);
} else {
throw new UnsupportedOperationException("This engine still not supported");
}
}
protected AIService(final AIConfiguration config, final Context context) {
this.config = config;
this.context = context;
aiDataService = new AIDataService(context, config);
}
/**
* Starts listening process
*/
public abstract void startListening();
/**
* Starts listening process. Request to the AI service will be done with specified contexts.
*/
public abstract void startListening(List<AIContext> contexts);
/**
* Starts listening process. Request to the AI service will be done with specified extra data.
* @param requestExtras extras can hold additional contexts and entities
*/
public abstract void startListening(RequestExtras requestExtras);
/**
* Stop listening and start request to the AI service with current recognition results
*/
public abstract void stopListening();
/**
* Cancel listening process and don't request to AI service
*/
public abstract void cancel();
/**
* Sets listener, which used to notify about process steps
* @param listener {@link AIListener AIListener} implementation
*/
public void setListener(final AIListener listener) {
this.listener = listener;
}
protected void onResult(final AIResponse response) {
if (listener != null) {
listener.onResult(response);
}
}
protected void onError(final AIError error) {
if (listener != null) {
listener.onError(error);
}
}
protected void onAudioLevelChanged(final float audioLevel) {
if (listener != null) {
listener.onAudioLevel(audioLevel);
}
}
protected void onListeningStarted() {
if (listener != null) {
listener.onListeningStarted();
}
}
protected void onListeningCancelled() {
if (listener != null) {
listener.onListeningCanceled();
}
}
protected void onListeningFinished() {
if (listener != null) {
listener.onListeningFinished();
}
}
public void pause() {
}
public void resume(){
}
public AIResponse textRequest(final AIRequest request) throws AIServiceException {
return aiDataService.request(request);
}
public AIResponse textRequest(final String textRequest, final RequestExtras requestExtras) throws AIServiceException {
final AIRequest aiRequest = new AIRequest(textRequest);
if (requestExtras != null) {
requestExtras.copyTo(aiRequest);
}
return aiDataService.request(aiRequest);
}
/**
* Forget all old contexts
* @return true if operation succeed, false otherwise
*/
public boolean resetContexts() {
return aiDataService.resetContexts();
}
/**
* Upload user entity for using while session
* @param userEntity entity to upload
* @return uploading result
* @throws AIServiceException
*/
public AIResponse uploadUserEntity(final Entity userEntity) throws AIServiceException {
return aiDataService.uploadUserEntity(userEntity);
}
/**
* Upload user entities for using while session
* @param userEntities collection of user entities
* @return uploading result
* @throws AIServiceException if request to the API.AI service failed
*/
public AIResponse uploadUserEntities(final Collection<Entity> userEntities) throws AIServiceException {
return aiDataService.uploadUserEntities(userEntities);
}
protected boolean checkPermissions() {
boolean granted = true;
try {
granted = ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
} catch (final Throwable ignored) {
}
return granted;
}
}
|
0
|
java-sources/ai/api/sdk/2.0.7/ai/api
|
java-sources/ai/api/sdk/2.0.7/ai/api/android/GsonFactory.java
|
package ai.api.android;
/***********************************************************************************************************************
*
* API.AI Android SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2014 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class GsonFactory {
public static Gson getGson(){
return ai.api.GsonFactory.getDefaultFactory().getGson();
}
}
|
0
|
java-sources/ai/api/sdk/2.0.7/ai/api
|
java-sources/ai/api/sdk/2.0.7/ai/api/android/SessionIdStorage.java
|
package ai.api.android;
/***********************************************************************************************************************
*
* API.AI Android SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
* *********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import java.util.UUID;
public abstract class SessionIdStorage {
private static final String PREF_NAME = "APIAI_preferences";
private static final String SESSION_ID = "sessionId";
public synchronized static String getSessionId(final Context context) {
final SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
final String sessionId = sharedPreferences.getString(SESSION_ID, "");
if (!TextUtils.isEmpty(sessionId)) {
return sessionId;
} else {
final SharedPreferences.Editor editor = sharedPreferences.edit();
final String value = UUID.randomUUID().toString();
editor.putString(SESSION_ID, value);
editor.commit();
return value;
}
}
public static synchronized void resetSessionId(final Context context) {
final SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
final SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(SESSION_ID, "");
editor.commit();
}
}
|
0
|
java-sources/ai/api/sdk/2.0.7/ai/api
|
java-sources/ai/api/sdk/2.0.7/ai/api/services/GoogleRecognitionServiceImpl.java
|
package ai.api.services;
/***********************************************************************************************************************
*
* API.AI Android SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import ai.api.android.AIConfiguration;
import ai.api.android.AIService;
import ai.api.AIServiceException;
import ai.api.PartialResultsListener;
import ai.api.RequestExtras;
import ai.api.model.AIContext;
import ai.api.model.AIError;
import ai.api.model.AIRequest;
import ai.api.model.AIResponse;
import ai.api.util.RecognizerChecker;
import ai.api.util.VersionConfig;
public class GoogleRecognitionServiceImpl extends AIService {
private static final String TAG = GoogleRecognitionServiceImpl.class.getName();
private static final long STOP_DELAY = 1000;
private SpeechRecognizer speechRecognizer;
private final Object speechRecognizerLock = new Object();
private RequestExtras requestExtras;
private PartialResultsListener partialResultsListener;
private final VersionConfig versionConfig;
private volatile boolean recognitionActive = false;
private volatile boolean wasReadyForSpeech;
private final Handler handler = new Handler();
private Runnable stopRunnable;
private final Map<Integer, String> errorMessages = new HashMap<>();
{
errorMessages.put(SpeechRecognizer.ERROR_NETWORK_TIMEOUT, "Network operation timed out.");
errorMessages.put(SpeechRecognizer.ERROR_NETWORK, "Other network related errors.");
errorMessages.put(SpeechRecognizer.ERROR_AUDIO, "Audio recording error.");
errorMessages.put(SpeechRecognizer.ERROR_SERVER, "Server sends error status.");
errorMessages.put(SpeechRecognizer.ERROR_CLIENT, "Other client side errors.");
errorMessages.put(SpeechRecognizer.ERROR_SPEECH_TIMEOUT, "No speech input.");
errorMessages.put(SpeechRecognizer.ERROR_NO_MATCH, "No recognition result matched.");
errorMessages.put(SpeechRecognizer.ERROR_RECOGNIZER_BUSY, "RecognitionService busy.");
errorMessages.put(SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS, "Insufficient permissions.");
}
public GoogleRecognitionServiceImpl(final Context context, final AIConfiguration config) {
super(config, context);
final ComponentName component = RecognizerChecker.findGoogleRecognizer(context);
if (component == null) {
Log.w(TAG, "Google Recognizer application not found on device. " +
"Quality of the recognition may be low. Please check if Google Search application installed and enabled.");
}
versionConfig = VersionConfig.init(context);
if (versionConfig.isAutoStopRecognizer()) {
stopRunnable = new Runnable() {
@Override
public void run() {
stopListening();
}
};
}
}
/**
* Manage recognizer cancellation runnable.
*
* @param action (int) (0 - stop, 1 - restart)
*/
private void updateStopRunnable(final int action) {
if (stopRunnable != null) {
if (action == 0) {
handler.removeCallbacks(stopRunnable);
} else if (action == 1) {
handler.removeCallbacks(stopRunnable);
handler.postDelayed(stopRunnable, STOP_DELAY);
}
}
}
protected void initializeRecognizer() {
if (speechRecognizer != null) {
return;
}
synchronized (speechRecognizerLock) {
if (speechRecognizer != null) {
speechRecognizer.destroy();
speechRecognizer = null;
}
final ComponentName component = RecognizerChecker.findGoogleRecognizer(context);
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(context, component);
speechRecognizer.setRecognitionListener(new InternalRecognitionListener());
}
}
protected void clearRecognizer() {
Log.d(TAG, "clearRecognizer");
if (speechRecognizer != null) {
synchronized (speechRecognizerLock) {
if (speechRecognizer != null) {
speechRecognizer.destroy();
speechRecognizer = null;
}
}
}
}
private void sendRequest(@NonNull final AIRequest aiRequest, @Nullable final RequestExtras requestExtras) {
if (aiRequest == null) {
throw new IllegalArgumentException("aiRequest must be not null");
}
final AsyncTask<AIRequest, Integer, AIResponse> task = new AsyncTask<AIRequest, Integer, AIResponse>() {
private AIError aiError;
@Override
protected AIResponse doInBackground(final AIRequest... params) {
final AIRequest request = params[0];
try {
return aiDataService.request(request, requestExtras);
} catch (final AIServiceException e) {
aiError = new AIError(e);
return null;
}
}
@Override
protected void onPostExecute(final AIResponse response) {
if (response != null) {
onResult(response);
} else {
onError(aiError);
}
}
};
task.execute(aiRequest);
}
@Override
public void startListening() {
startListening(new RequestExtras());
}
@Override
public void startListening(final List<AIContext> contexts) {
startListening(new RequestExtras(contexts, null));
}
@Override
public void startListening(final RequestExtras requestExtras) {
if (!recognitionActive) {
synchronized (speechRecognizerLock) {
this.requestExtras = requestExtras;
if (!checkPermissions()) {
final AIError aiError = new AIError("RECORD_AUDIO permission is denied. Please request permission from user.");
onError(aiError);
return;
}
initializeRecognizer();
recognitionActive = true;
final Intent sttIntent = createRecognitionIntent();
try {
wasReadyForSpeech = false;
speechRecognizer.startListening(sttIntent);
} catch (final SecurityException e) { //Error occurs only on HTC devices.
}
}
} else {
Log.w(TAG, "Trying to start recognition while another recognition active");
if (!wasReadyForSpeech) {
cancel();
}
}
}
private Intent createRecognitionIntent() {
final Intent sttIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
sttIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
final String language = config.getLanguage().replace('-', '_');
sttIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language);
sttIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, language);
sttIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
sttIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, context.getPackageName());
// WORKAROUND for https://code.google.com/p/android/issues/detail?id=75347
sttIntent.putExtra("android.speech.extra.EXTRA_ADDITIONAL_LANGUAGES", new String[]{language});
return sttIntent;
}
@Override
public void stopListening() {
synchronized (speechRecognizerLock) {
if (speechRecognizer != null) {
speechRecognizer.stopListening();
}
}
}
@Override
public void cancel() {
synchronized (speechRecognizerLock) {
if (recognitionActive) {
recognitionActive = false;
if (speechRecognizer != null) {
speechRecognizer.cancel();
}
onListeningCancelled();
}
}
}
private void restartRecognition() {
updateStopRunnable(0);
recognitionActive = false;
synchronized (speechRecognizerLock) {
try {
if (speechRecognizer != null) {
speechRecognizer.cancel();
final Intent intent = createRecognitionIntent();
wasReadyForSpeech = false;
speechRecognizer.startListening(intent);
recognitionActive = true;
}
} catch (Exception e) {
stopListening();
}
}
}
/**
* This method must be called from UI thread
*/
@Override
public void pause() {
clearRecognizer();
}
/**
* This method must be called from UI thread
*/
@Override
public void resume() {
}
public void setPartialResultsListener(PartialResultsListener partialResultsListener) {
this.partialResultsListener = partialResultsListener;
}
protected void onPartialResults(final List<String> partialResults) {
if (partialResultsListener != null) {
partialResultsListener.onPartialResults(partialResults);
}
}
private void stopInternal() {
updateStopRunnable(0);
if (versionConfig.isDestroyRecognizer()) clearRecognizer();
recognitionActive = false;
}
private class InternalRecognitionListener implements RecognitionListener {
@Override
public void onReadyForSpeech(final Bundle params) {
if (recognitionActive) {
onListeningStarted();
}
wasReadyForSpeech = true;
}
@Override
public void onBeginningOfSpeech() {
}
@Override
public void onRmsChanged(final float rmsdB) {
if (recognitionActive) {
onAudioLevelChanged(rmsdB);
}
}
@Override
public void onBufferReceived(final byte[] buffer) {
}
@Override
public void onEndOfSpeech() {
if (recognitionActive) {
onListeningFinished();
}
}
@Override
public void onError(final int error) {
if (error == SpeechRecognizer.ERROR_NO_MATCH && !wasReadyForSpeech) {
Log.d(TAG, "SpeechRecognizer.ERROR_NO_MATCH, restartRecognition()");
restartRecognition();
return;
}
if (recognitionActive) {
final AIError aiError;
if (errorMessages.containsKey(error)) {
final String description = errorMessages.get(error);
aiError = new AIError("Speech recognition engine error: " + description);
} else {
aiError = new AIError("Speech recognition engine error: " + error);
}
GoogleRecognitionServiceImpl.this.onError(aiError);
}
stopInternal();
}
@TargetApi(14)
@Override
public void onResults(final Bundle results) {
if (recognitionActive) {
final ArrayList<String> recognitionResults = results
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
float[] rates = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
rates = results.getFloatArray(SpeechRecognizer.CONFIDENCE_SCORES);
}
if (recognitionResults == null || recognitionResults.isEmpty()) {
// empty response
GoogleRecognitionServiceImpl.this.onResult(new AIResponse());
} else {
final AIRequest aiRequest = new AIRequest();
if (rates != null) {
aiRequest.setQuery(recognitionResults.toArray(new String[recognitionResults.size()]), rates);
} else {
aiRequest.setQuery(recognitionResults.get(0));
}
// notify listeners about the last recogntion result for more accurate user feedback
GoogleRecognitionServiceImpl.this.onPartialResults(recognitionResults);
GoogleRecognitionServiceImpl.this.sendRequest(aiRequest, requestExtras);
}
}
stopInternal();
}
@Override
public void onPartialResults(final Bundle partialResults) {
if (recognitionActive) {
updateStopRunnable(1);
final ArrayList<String> partialRecognitionResults = partialResults.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (partialRecognitionResults != null && !partialRecognitionResults.isEmpty()) {
GoogleRecognitionServiceImpl.this.onPartialResults(partialRecognitionResults);
}
}
}
@Override
public void onEvent(final int eventType, final Bundle params) {
}
}
}
|
0
|
java-sources/ai/api/sdk/2.0.7/ai/api
|
java-sources/ai/api/sdk/2.0.7/ai/api/services/SpeaktoitRecognitionServiceImpl.java
|
package ai.api.services;
/***********************************************************************************************************************
*
* API.AI Android SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2014 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import ai.api.AIServiceException;
import ai.api.RequestExtras;
import ai.api.android.AIConfiguration;
import ai.api.android.AIService;
import ai.api.model.AIContext;
import ai.api.model.AIError;
import ai.api.model.AIResponse;
import ai.api.util.VoiceActivityDetector;
import static ai.api.util.VoiceActivityDetector.FRAME_SIZE_IN_BYTES;
import static ai.api.util.VoiceActivityDetector.NOISE_BYTES;
/*
* @deprecated Use GoogleRecognitionServiceImpl
*/
@Deprecated
public class SpeaktoitRecognitionServiceImpl extends AIService implements
VoiceActivityDetector.SpeechEventsListener,
MediaPlayer.OnCompletionListener,
MediaPlayer.OnErrorListener {
public static final String TAG = SpeaktoitRecognitionServiceImpl.class.getName();
private static final int SAMPLE_RATE_IN_HZ = 16000;
private static final int CHANNEL_CONFIG = AudioFormat.CHANNEL_IN_MONO;
private static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
private final ExecutorService eventsExecutor = Executors.newSingleThreadExecutor();
private final VoiceActivityDetector vad = new VoiceActivityDetector(SAMPLE_RATE_IN_HZ);
private AudioRecord audioRecord;
private final Object recognizerLock = new Object();
private volatile boolean isRecording = false;
private MediaPlayer mediaPlayer;
private RequestExtras extras;
private RecognizeTask recognizeTask;
public SpeaktoitRecognitionServiceImpl(final Context context, final AIConfiguration config) {
super(config, context);
init();
}
private void init() {
synchronized (recognizerLock) {
final int bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE_IN_HZ, CHANNEL_CONFIG, AUDIO_FORMAT);
audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
SAMPLE_RATE_IN_HZ,
CHANNEL_CONFIG,
AUDIO_FORMAT,
bufferSize);
vad.setEnabled(config.isVoiceActivityDetectionEnabled());
vad.setSpeechListener(this);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnCompletionListener(this);
}
}
@Override
public void startListening() {
startListening(new RequestExtras());
}
@Override
public void startListening(final List<AIContext> contexts) {
startListening(new RequestExtras(contexts, null));
}
@Override
public void startListening(final RequestExtras requestExtras) {
synchronized (recognizerLock) {
if (!isRecording) {
if (!checkPermissions()) {
final AIError aiError = new AIError("RECORD_AUDIO permission is denied. Please request permission from user.");
onError(aiError);
return;
}
isRecording = true;
extras = requestExtras;
final AssetFileDescriptor startSound = config.getRecognizerStartSound();
if (startSound != null) {
final boolean success = playSound(startSound);
if (!success) {
startRecording(extras);
}
} else {
startRecording(extras);
}
} else {
Log.w(TAG, "Trying start listening when it already active");
}
}
}
private void startRecording(final RequestExtras extras) {
vad.reset();
audioRecord.startRecording();
onListeningStarted();
recognizeTask = new RecognizeTask(new RecorderStream(audioRecord), extras);
recognizeTask.execute();
}
@Override
public void stopListening() {
synchronized (recognizerLock) {
if (isRecording) {
try {
audioRecord.stop();
isRecording = false;
final AssetFileDescriptor stopSound = config.getRecognizerStopSound();
if (stopSound != null) {
playSound(stopSound);
}
onListeningFinished();
} catch (final IllegalStateException e) {
Log.w(TAG, "Attempt to stop audioRecord when it is stopped");
}
}
}
}
@Override
public void cancel() {
synchronized (recognizerLock) {
if (isRecording) {
audioRecord.stop();
isRecording = false;
final AssetFileDescriptor cancelSound = config.getRecognizerCancelSound();
if (cancelSound != null) {
playSound(cancelSound);
}
}
if (recognizeTask != null) {
recognizeTask.cancel(true);
}
onListeningCancelled();
}
}
@Override
public void pause() {
synchronized (recognizerLock) {
if (isRecording) {
audioRecord.stop();
isRecording = false;
}
audioRecord.release();
audioRecord = null;
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
@Override
public void resume() {
init();
}
private boolean playSound(AssetFileDescriptor afd) {
boolean result = true;
try {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
result = false;
}
return result;
}
@Override
public void onSpeechBegin() {
}
@Override
public void onSpeechEnd() {
eventsExecutor.submit(new Runnable() {
@Override
public void run() {
stopListening();
}
});
}
@Override
public void onSpeechCancel() {
eventsExecutor.submit(new Runnable() {
@Override
public void run() {
cancel();
}
});
}
private class RecorderStream extends InputStream {
@SuppressWarnings("MagicNumber")
private final float dbLevel = (float) Math.pow(10.0, -1.0 / 20.0);
private final AudioRecord audioRecord;
private byte[] bytes;
private final Object bytesLock = new Object();
int offset = 0;
int max = 0;
int min = 0;
float alignment = 0;
float count = 1;
int extent;
private RecorderStream(final AudioRecord audioRecord) {
this.audioRecord = audioRecord;
}
@Override
public int read() throws IOException {
final byte[] buffer = new byte[1];
audioRecord.read(buffer, 0, 1);
return buffer[0];
}
@Override
public int read(@NonNull final byte[] buffer, final int byteOffset, final int byteCount) throws IOException {
final int bytesRead = audioRecord.read(buffer, byteOffset, byteCount);
if (bytesRead > 0) {
synchronized (bytesLock) {
if (config.isNormalizeInputSound())
normalize(buffer, bytesRead);
byte[] temp = bytes;
int tempLength = temp != null ? temp.length : 0;
bytes = new byte[tempLength + bytesRead];
if (tempLength > 0) {
System.arraycopy(temp, 0, bytes, 0, tempLength);
}
System.arraycopy(buffer, 0, bytes, tempLength, bytesRead);
while (bytes.length >= FRAME_SIZE_IN_BYTES) {
final byte[] b = new byte[FRAME_SIZE_IN_BYTES];
System.arraycopy(bytes, 0, b, 0, FRAME_SIZE_IN_BYTES);
vad.processBuffer(b, FRAME_SIZE_IN_BYTES);
temp = bytes;
final int newLength = temp.length - FRAME_SIZE_IN_BYTES;
bytes = new byte[newLength];
System.arraycopy(temp, FRAME_SIZE_IN_BYTES, bytes, 0, newLength);
}
onAudioLevelChanged((float) vad.calculateRms());
}
}
return bytesRead != 0 ? bytesRead : AudioRecord.ERROR_INVALID_OPERATION;
}
private void normalize(@NonNull final byte[] buffer, final int bytesRead) {
final int remainOffset = NOISE_BYTES - offset;
if (bytesRead >= remainOffset) {
final ByteBuffer byteBuffer = ByteBuffer.wrap(buffer, remainOffset, bytesRead - remainOffset).order(ByteOrder.LITTLE_ENDIAN);
final ShortBuffer shorts = byteBuffer.asShortBuffer();
for (int i = 0; i < shorts.limit(); i++) {
final short sample = shorts.get(i);
max = Math.max(max, sample);
min = Math.min(min, sample);
alignment = (count - 1) / count * alignment + sample / count;
count++;
}
extent = Math.max(Math.abs(max), Math.abs(min));
final float factor = dbLevel * Short.MAX_VALUE / extent;
for (int i = 0; i < shorts.limit(); i++) {
byteBuffer.putShort((short) ((shorts.get(i) - alignment) * factor));
}
}
offset += Math.min(bytesRead, remainOffset);
}
}
private class RecognizeTask extends AsyncTask<Void, Void, AIResponse> {
private final RecorderStream recorderStream;
private final RequestExtras requestExtras;
private AIError aiError;
private RecognizeTask(final RecorderStream recorderStream, final RequestExtras requestExtras) {
this.recorderStream = recorderStream;
this.requestExtras = requestExtras;
}
@Override
protected AIResponse doInBackground(final Void... params) {
try {
return aiDataService.voiceRequest(recorderStream, requestExtras);
} catch (final AIServiceException e) {
aiError = new AIError(e);
}
return null;
}
@Override
protected void onPostExecute(final AIResponse aiResponse) {
if (isCancelled()) {
return;
}
if (aiResponse != null) {
onResult(aiResponse);
} else {
SpeaktoitRecognitionServiceImpl.this.cancel();
onError(aiError);
}
}
}
@Override
public void onCompletion(MediaPlayer mp) {
if (isRecording) {
startRecording(extras);
}
}
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
if (isRecording) {
startRecording(extras);
}
return false;
}
}
|
0
|
java-sources/ai/api/sdk/2.0.7/ai/api
|
java-sources/ai/api/sdk/2.0.7/ai/api/ui/AIButton.java
|
package ai.api.ui;
/***********************************************************************************************************************
*
* API.AI Android SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;
import java.util.List;
import ai.api.android.AIConfiguration;
import ai.api.AIListener;
import ai.api.android.AIService;
import ai.api.AIServiceException;
import ai.api.PartialResultsListener;
import ai.api.R;
import ai.api.RequestExtras;
import ai.api.model.AIError;
import ai.api.model.AIRequest;
import ai.api.model.AIResponse;
import ai.api.services.GoogleRecognitionServiceImpl;
public class AIButton extends SoundLevelButton implements AIListener {
public interface AIButtonListener {
void onResult(final AIResponse result);
void onError(final AIError error);
void onCancelled();
}
private static final String TAG = AIButton.class.getName();
protected static final int[] STATE_WAITING = {R.attr.state_waiting};
protected static final int[] STATE_SPEAKING = {R.attr.state_speaking};
protected static final int[] STATE_INITIALIZING_TTS = {R.attr.state_initializing_tts};
private float animationStage = 0;
private boolean animationSecondPhase = false;
private final WaitingAnimation animation = new WaitingAnimation();
private AIService aiService;
private AIButtonListener resultsListener;
private PartialResultsListener partialResultsListener;
@Override
public void onResult(final AIResponse result) {
post(new Runnable() {
@Override
public void run() {
changeState(MicState.normal);
}
});
if (resultsListener != null) {
resultsListener.onResult(result);
}
}
@Override
public void onError(final AIError error) {
post(new Runnable() {
@Override
public void run() {
changeState(MicState.normal);
}
});
if (resultsListener != null) {
resultsListener.onError(error);
}
}
@Override
public void onAudioLevel(final float level) {
setSoundLevel(level);
}
@Override
public void onListeningStarted() {
post(new Runnable() {
@Override
public void run() {
changeState(MicState.listening);
}
});
}
@Override
public void onListeningCanceled() {
post(new Runnable() {
@Override
public void run() {
changeState(MicState.normal);
}
});
if (resultsListener != null) {
resultsListener.onCancelled();
}
}
@Override
public void onListeningFinished() {
post(new Runnable() {
@Override
public void run() {
changeState(MicState.busy);
}
});
}
public enum MicState {
normal,
busy, // transitive state with disabled mic
listening, // state with sound indicator
speaking,
initializingTts;
public static MicState fromAttrs(final TypedArray viewAttrs) {
if (viewAttrs.getBoolean(R.styleable.SoundLevelButton_state_listening, false))
return listening;
if (viewAttrs.getBoolean(R.styleable.SoundLevelButton_state_waiting, false))
return busy;
if (viewAttrs.getBoolean(R.styleable.SoundLevelButton_state_speaking, false))
return speaking;
if (viewAttrs.getBoolean(R.styleable.SoundLevelButton_state_initializing_tts, false))
return initializingTts;
return normal;
}
}
private volatile MicState currentState = MicState.normal;
public AIButton(final Context context) {
super(context);
init(context, null);
}
public AIButton(final Context context, final AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public AIButton(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
private void init(final Context context, final AttributeSet attrs) {
if (attrs != null) {
final TypedArray viewAttrs = context.obtainStyledAttributes(attrs, R.styleable.SoundLevelButton);
try {
currentState = MicState.fromAttrs(viewAttrs);
} finally {
viewAttrs.recycle();
}
}
}
public void initialize(final AIConfiguration config) {
aiService = AIService.getService(getContext(), config);
aiService.setListener(this);
if (aiService instanceof GoogleRecognitionServiceImpl) {
((GoogleRecognitionServiceImpl) aiService).setPartialResultsListener(new PartialResultsListener() {
@Override
public void onPartialResults(final List<String> partialResults) {
if (partialResultsListener != null) {
partialResultsListener.onPartialResults(partialResults);
}
}
});
}
}
public void setResultsListener(final AIButtonListener resultsListener) {
this.resultsListener = resultsListener;
}
public void setPartialResultsListener(final PartialResultsListener partialResultsListener) {
this.partialResultsListener = partialResultsListener;
}
public void startListening() {
startListening(null);
}
public void startListening(final RequestExtras requestExtras) {
if (aiService != null) {
if (currentState == MicState.normal) {
aiService.startListening(requestExtras);
}
} else {
throw new IllegalStateException("Call initialize method before usage");
}
}
public AIResponse textRequest(final AIRequest request) throws AIServiceException {
if (aiService != null) {
return aiService.textRequest(request);
} else {
throw new IllegalStateException("Call initialize method before usage");
}
}
public AIResponse textRequest(final String request) throws AIServiceException {
return textRequest(new AIRequest(request));
}
/**
* Get AIService object for making different data requests
* @return
*/
public AIService getAIService() {
return aiService;
}
@Override
protected void onClick(final View v) {
super.onClick(v);
if (aiService != null) {
switch (currentState) {
case normal:
aiService.startListening();
break;
case busy:
aiService.cancel();
break;
default:
aiService.stopListening();
break;
}
}
}
@Override
public int[] onCreateDrawableState(final int extraSpace) {
final int[] state = super.onCreateDrawableState(extraSpace + 1);
if (currentState != null) {
switch (currentState) {
case normal:
break;
case busy:
mergeDrawableStates(state, STATE_WAITING);
break;
case listening:
mergeDrawableStates(state, STATE_LISTENING);
break;
case speaking:
mergeDrawableStates(state, STATE_SPEAKING);
break;
case initializingTts:
mergeDrawableStates(state, STATE_INITIALIZING_TTS);
break;
}
}
return state;
}
public void resume() {
if (aiService != null) {
aiService.resume();
}
}
public void pause() {
cancelListening();
if (aiService != null) {
aiService.pause();
}
}
private void cancelListening() {
if (aiService != null) {
if (currentState != MicState.normal) {
aiService.cancel();
changeState(MicState.normal);
}
}
}
protected void changeState(final MicState toState) {
switch (toState) {
case normal:
stopProcessingAnimation();
setDrawSoundLevel(false);
break;
case busy:
startProcessingAnimation();
setDrawSoundLevel(false);
break;
case listening:
stopProcessingAnimation();
setDrawSoundLevel(true);
break;
case speaking:
stopProcessingAnimation();
setDrawSoundLevel(false);
break;
case initializingTts:
stopProcessingAnimation();
setDrawSoundLevel(false);
break;
}
currentState = toState;
refreshDrawableState();
}
protected MicState getCurrentState() {
return currentState;
}
private void startProcessingAnimation() {
setDrawCenter(true);
animationSecondPhase = false;
startAnimation(animation);
}
private void stopProcessingAnimation() {
setDrawCenter(false);
clearAnimation();
animationStage = 0;
animationSecondPhase = false;
postInvalidate();
}
@Override
protected String getDebugState() {
return super.getDebugState() + "\nst:" + currentState;
}
private class WaitingAnimation extends Animation {
protected WaitingAnimation() {
super();
setDuration(1500);
this.setRepeatCount(INFINITE);
this.setRepeatMode(RESTART);
this.setInterpolator(new LinearInterpolator());
}
@Override
protected void applyTransformation(final float interpolatedTime, final Transformation t) {
animationStage = interpolatedTime;
invalidate();
}
}
@Override
protected void onDraw(final Canvas canvas) {
super.onDraw(canvas);
if (animationStage > 0 || animationSecondPhase) {
final float center = getWidth() / 2f;
final float radius = getMinRadius() * 1.25f;
final RectF size = new RectF(center - radius, center - radius, center + radius, center + radius);
final Paint paint = new Paint();
paint.setColor(getResources().getColor(R.color.icon_orange_color));
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(dpToPixels(this.getContext(), 4));
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setAntiAlias(true);
final float startingAngle;
final float sweepAngle;
if (animationStage < 0.5 && !animationSecondPhase) {
startingAngle = 0;
sweepAngle = animationStage * 360;
} else {
startingAngle = (animationStage - 0.5f) * 360;
sweepAngle = 180;
animationSecondPhase = true;
}
canvas.drawArc(size, 270f + startingAngle, sweepAngle, false, paint);
}
}
private static int dpToPixels(final Context context, final float dp) {
final Resources r = context.getResources();
return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));
}
}
|
0
|
java-sources/ai/api/sdk/2.0.7/ai/api
|
java-sources/ai/api/sdk/2.0.7/ai/api/ui/AIDialog.java
|
package ai.api.ui;
/***********************************************************************************************************************
*
* API.AI Android SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.Window;
import android.widget.TextView;
import java.util.List;
import ai.api.android.AIConfiguration;
import ai.api.android.AIService;
import ai.api.AIServiceException;
import ai.api.PartialResultsListener;
import ai.api.R;
import ai.api.model.AIError;
import ai.api.model.AIRequest;
import ai.api.model.AIResponse;
public class AIDialog {
private static final String TAG = AIDialog.class.getName();
private final Context context;
private final AIConfiguration config;
private AIDialogListener resultsListener;
private final Dialog dialog;
private final AIButton aiButton;
private final TextView partialResultsTextView;
private final Handler handler;
public interface AIDialogListener {
void onResult(final AIResponse result);
void onError(final AIError error);
void onCancelled();
}
public AIDialog(final Context context, final AIConfiguration config) {
this(context, config, R.layout.aidialog);
}
public AIDialog(final Context context, final AIConfiguration config, final int customLayout) {
this.context = context;
this.config = config;
dialog = new Dialog(context);
handler = new Handler(Looper.getMainLooper());
dialog.setCanceledOnTouchOutside(true);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(customLayout);
partialResultsTextView = (TextView) dialog.findViewById(R.id.partialResultsTextView);
aiButton = (AIButton) dialog.findViewById(R.id.micButton);
aiButton.initialize(config);
setAIButtonCallback(aiButton);
}
public void setResultsListener(final AIDialogListener resultsListener) {
this.resultsListener = resultsListener;
}
public Dialog getDialog() {
return dialog;
}
public void showAndListen() {
handler.post(new Runnable() {
@Override
public void run() {
resetControls();
dialog.show();
startListening();
}
});
}
public AIResponse textRequest(final AIRequest request) throws AIServiceException {
return aiButton.textRequest(request);
}
public AIResponse textRequest(final String request) throws AIServiceException {
return textRequest(new AIRequest(request));
}
private void resetControls() {
if (partialResultsTextView != null) {
partialResultsTextView.setText("");
}
}
private void setAIButtonCallback(final AIButton aiButton) {
aiButton.setResultsListener(new AIButton.AIButtonListener() {
@Override
public void onResult(final AIResponse result) {
AIDialog.this.close();
if (resultsListener != null) {
resultsListener.onResult(result);
}
}
@Override
public void onError(final AIError error) {
if (resultsListener != null) {
resultsListener.onError(error);
}
}
@Override
public void onCancelled() {
AIDialog.this.close();
if (resultsListener != null) {
resultsListener.onCancelled();
}
}
});
aiButton.setPartialResultsListener(new PartialResultsListener() {
@Override
public void onPartialResults(final List<String> partialResults) {
final String result = partialResults.get(0);
if (!TextUtils.isEmpty(result)) {
handler.post(new Runnable() {
@Override
public void run() {
if (partialResultsTextView != null) {
partialResultsTextView.setText(result);
}
}
});
}
}
});
}
private void startListening() {
if (aiButton != null) {
aiButton.startListening();
}
}
public void close() {
handler.post(new Runnable() {
@Override
public void run() {
dialog.dismiss();
}
});
}
/**
* Get AIService object for making different data requests
* @return
*/
public AIService getAIService() {
return aiButton.getAIService();
}
/**
* Disconnect aiDialog from the recognition service.
* Use pause/resume methods when you have permanent reference to the AIDialog object in your Activity.
* pause() call should be added to the onPause() method of the Activity.
* resume() call should be added to the onResume() method of the Activity.
*/
public void pause() {
if (aiButton != null) {
aiButton.pause();
}
}
/**
* Reconnect aiDialog to the recognition service.
* Use pause/resume methods when you have permanent reference to the AIDialog object in your Activity.
* pause() call should be added to the onPause() method of the Activity.
* resume() call should be added to the onResume() method of the Activity.
*/
public void resume() {
if (aiButton != null) {
aiButton.resume();
}
}
}
|
0
|
java-sources/ai/api/sdk/2.0.7/ai/api
|
java-sources/ai/api/sdk/2.0.7/ai/api/ui/MaskedColorView.java
|
package ai.api.ui;
/***********************************************************************************************************************
*
* API.AI Android SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2014 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Build;
import android.util.AttributeSet;
import android.widget.ImageView;
import ai.api.R;
/**
* ImageView
* src used as a mask, and MaskedColorView_mainColor as a color or state color list
*/
public class MaskedColorView extends ImageView {
private ColorStateList colorStateList = null;
public MaskedColorView(final Context context) {
super(context, null);
}
public MaskedColorView(final Context context, final AttributeSet attrs) {
super(context, attrs, android.R.attr.imageButtonStyle);
configure(attrs);
}
public MaskedColorView(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
configure(attrs);
}
@TargetApi(11)
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
setColorFilter(getCurrentColor(getDrawableState()), PorterDuff.Mode.SRC_ATOP);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
jumpDrawablesToCurrentState();
}
}
public void setColorStateList(final ColorStateList colorStateList) {
this.colorStateList = colorStateList;
}
private int getCurrentColor(final int[] stateSet) {
return colorStateList == null
? Color.MAGENTA
: colorStateList.getColorForState(stateSet, colorStateList.getDefaultColor());
}
private void configure(final AttributeSet attrs) {
if (attrs != null) {
final TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.MaskedColorView);
try {
final ColorStateList csl = a.getColorStateList(R.styleable.MaskedColorView_mainColor);
if (csl != null) {
colorStateList = csl;
}
} finally {
a.recycle();
}
}
}
protected String getDebugState() {
return "====\ncsl is " + (colorStateList != null ? "NOT" : "") + " null";
}
}
|
0
|
java-sources/ai/api/sdk/2.0.7/ai/api
|
java-sources/ai/api/sdk/2.0.7/ai/api/ui/SoundLevelButton.java
|
package ai.api.ui;
/***********************************************************************************************************************
*
* API.AI Android SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2014 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import ai.api.R;
public class SoundLevelButton extends MaskedColorView {
private static final String TAG = SoundLevelButton.class.getName();
protected static final int[] STATE_LISTENING = new int[] { R.attr.state_listening };
private final SoundLevelCircleDrawable backgroundDrawable;
protected boolean listening = false;
@SuppressWarnings("UnusedDeclaration")
public SoundLevelButton(@NonNull final Context context) {
super(context);
backgroundDrawable = new SoundLevelCircleDrawable(getParams(context, null));
setCircleBackground(backgroundDrawable);
init();
}
@SuppressWarnings("UnusedDeclaration")
public SoundLevelButton(@NonNull final Context context, @Nullable final AttributeSet attrs) {
super(context, attrs);
backgroundDrawable = new SoundLevelCircleDrawable(getParams(context, attrs));
setCircleBackground(backgroundDrawable);
init();
}
@SuppressWarnings("UnusedDeclaration")
public SoundLevelButton(@NonNull final Context context, @Nullable final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
backgroundDrawable = new SoundLevelCircleDrawable(getParams(context, attrs));
setCircleBackground(backgroundDrawable);
init();
}
private void init() {
setOnClickListener(new OnClickListener() {
@Override
public void onClick(final View v) {
SoundLevelButton.this.onClick(v);
}
});
}
protected void onClick(final View v) {
}
@Nullable
private SoundLevelCircleDrawable.Params getParams(@NonNull final Context context, @Nullable final AttributeSet attrs) {
if (attrs != null) {
final TypedArray viewAttrs = context.obtainStyledAttributes(attrs, R.styleable.SoundLevelButton);
try {
this.listening = viewAttrs.getBoolean(R.styleable.SoundLevelButton_state_listening, false);
final float maxRadius = viewAttrs.getDimension(R.styleable.SoundLevelButton_maxRadius, -1);
final float minRadius = viewAttrs.getDimension(R.styleable.SoundLevelButton_minRadius, -1);
final float circleCenterX = viewAttrs.getDimension(R.styleable.SoundLevelButton_circleCenterX, -1);
final float circleCenterY = viewAttrs.getDimension(R.styleable.SoundLevelButton_circleCenterY, -1);
final int centerColor = viewAttrs.getColor(R.styleable.SoundLevelButton_centerColor, SoundLevelCircleDrawable.CENTER_COLOR_DEF);
final int haloColor = viewAttrs.getColor(R.styleable.SoundLevelButton_haloColor, SoundLevelCircleDrawable.HALO_COLOR_DEF);
return new SoundLevelCircleDrawable.Params(maxRadius, minRadius, circleCenterX, circleCenterY, centerColor, haloColor);
} finally {
viewAttrs.recycle();
}
}
return null;
}
@Override
public int[] onCreateDrawableState(final int extraSpace) {
final int[] state = super.onCreateDrawableState(extraSpace + 1);
if (listening) mergeDrawableStates(state, STATE_LISTENING);
return state;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void setCircleBackground(final SoundLevelCircleDrawable soundLevelCircleDrawable) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
//noinspection deprecation
setBackgroundDrawable(soundLevelCircleDrawable);
else
setBackground(soundLevelCircleDrawable);
}
public void setDrawSoundLevel(final boolean drawSoundLevel) {
listening = drawSoundLevel;
backgroundDrawable.setDrawSoundLevel(drawSoundLevel);
refreshDrawableState();
postInvalidate();
}
protected void setDrawCenter(final boolean drawCenter) {
this.backgroundDrawable.setDrawCenter(drawCenter);
}
public void setSoundLevel(final float soundLevel) {
backgroundDrawable.setSoundLevel(soundLevel);
postInvalidate();
}
@Override
protected String getDebugState() {
return super.getDebugState() + "\ndrawSL: " + listening;
}
protected float getMinRadius() {
return backgroundDrawable.getMinRadius();
}
}
|
0
|
java-sources/ai/api/sdk/2.0.7/ai/api
|
java-sources/ai/api/sdk/2.0.7/ai/api/ui/SoundLevelCircleDrawable.java
|
package ai.api.ui;
/***********************************************************************************************************************
*
* API.AI Android SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2014 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
public class SoundLevelCircleDrawable extends Drawable {
public static final int HALO_COLOR_DEF = Color.argb(16, 0x0, 0x0, 0x0);
public static final int CENTER_COLOR_DEF = 0xffF26C29;
private static final float MIN_VALUE = 1f / 2;
private static final float MAX_VALUE = 10;
private static final float INITIAL_VALUE = 2.5f;
private final float maxRadius;
private final float minRadius;
private final float circleCenterX;
private final float circleCenterY;
private float minMicLevel = MIN_VALUE;
private float maxMicLevel = MAX_VALUE;
private boolean drawSoundLevel = false;
private final Paint paintIndicatorHalo;
private final Paint paintIndicatorCenter;
private float smoothedLevel = INITIAL_VALUE;
private final Rect bounds = new Rect();
private boolean drawCenter = false;
private static Paint newColorPaint(final int color) {
final Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
paint.setColor(color);
return paint;
}
public SoundLevelCircleDrawable() {
this(null);
}
public SoundLevelCircleDrawable(@Nullable final Params params) {
final int centerColor;
final int haloColor;
if (params != null) {
this.maxRadius = params.maxRadius;
this.minRadius = params.minRadius;
this.circleCenterX = params.circleCenterX;
this.circleCenterY = params.circleCenterY;
centerColor = params.centerColor;
haloColor = params.haloColor;
} else {
this.maxRadius = -1;
this.minRadius = -1;
this.circleCenterX = -1;
this.circleCenterY = -1;
centerColor = CENTER_COLOR_DEF;
haloColor = HALO_COLOR_DEF;
}
paintIndicatorHalo = newColorPaint(haloColor);
paintIndicatorCenter = newColorPaint(centerColor);
}
@SuppressWarnings("MagicNumber")
@Override
public void draw(final Canvas canvas) {
if (drawSoundLevel || drawCenter) {
canvas.save();
try {
if (this.maxRadius < 0 || this.circleCenterX < 0 || this.circleCenterY < 0)
canvas.getClipBounds(bounds);
canvas.drawColor(Color.TRANSPARENT);
final float levelInFraction = (smoothedLevel - minMicLevel) / (maxMicLevel - minMicLevel);
final float maxRadius = this.maxRadius < 0 ? bounds.width() / 2f : this.maxRadius;
final float minRadius = this.minRadius < 0 ? maxRadius * (65 / 112.5f) : this.minRadius;
final float soundMinRadius = minRadius * 0.8f; //to hide halo on silence
final float rangeRadius = maxRadius - soundMinRadius;
final float soundRadius = soundMinRadius + rangeRadius * levelInFraction;
final float x = this.circleCenterX < 0 ? bounds.width() / 2f : this.circleCenterX;
final float y = this.circleCenterY < 0 ? bounds.height() / 2f : this.circleCenterY;
if (drawSoundLevel)
canvas.drawCircle(x, y, soundRadius, paintIndicatorHalo);
if (drawCenter || drawSoundLevel)
canvas.drawCircle(x, y, minRadius, paintIndicatorCenter);
} finally {
canvas.restore();
}
}
}
@Override
public void setAlpha(final int ignored) {
//ignore
}
@Override
public void setColorFilter(final ColorFilter ignored) {
//ignore
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
/**
* @param drawSoundLevel true to draw
* @return true if drawSoundLevel changed
*/
public boolean setDrawSoundLevel(final boolean drawSoundLevel) {
if (this.drawSoundLevel != drawSoundLevel) {
this.drawSoundLevel = drawSoundLevel;
if (drawSoundLevel) {
minMicLevel = MIN_VALUE;
maxMicLevel = MAX_VALUE;
smoothedLevel = INITIAL_VALUE;
}
return true;
} else
return false;
}
public void setDrawCenter(final boolean drawCenter) {
this.drawCenter = drawCenter;
}
public void setSoundLevel(final float soundLevel) {
final float positiveSoundLevel = Math.abs(soundLevel);
if (positiveSoundLevel < minMicLevel) {
minMicLevel = (minMicLevel + positiveSoundLevel) / 2; // average
}
if (positiveSoundLevel > maxMicLevel) {
maxMicLevel = (maxMicLevel + positiveSoundLevel) / 2; // average
}
final float alpha = 0.2f;
smoothedLevel = (smoothedLevel * (1 - alpha) + (positiveSoundLevel * alpha));
if (smoothedLevel > maxMicLevel) {
smoothedLevel = maxMicLevel;
} else if (smoothedLevel < minMicLevel) {
smoothedLevel = minMicLevel;
}
}
public float getMinRadius() {
return minRadius;
}
public static class Params {
public final float maxRadius;
public final float minRadius;
public final float circleCenterX;
public final float circleCenterY;
private final int centerColor;
private final int haloColor;
public Params(final float maxRadius, final float minRadius, final float circleCenterX, final float circleCenterY, final int centerColor, final int haloColor) {
this.maxRadius = maxRadius;
this.minRadius = minRadius;
this.circleCenterX = circleCenterX;
this.circleCenterY = circleCenterY;
this.centerColor = centerColor;
this.haloColor = haloColor;
}
}
}
|
0
|
java-sources/ai/api/sdk/2.0.7/ai/api
|
java-sources/ai/api/sdk/2.0.7/ai/api/util/BluetoothController.java
|
package ai.api.util;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.CountDownTimer;
import android.util.Log;
public abstract class BluetoothController {
private Context mContext;
private BluetoothAdapter mBluetoothAdapter;
private AudioManager mAudioManager;
private boolean mIsCountDownOn;
private boolean mIsStarting;
private boolean mIsOnHeadsetSco;
private boolean mIsStarted;
private static final String TAG = "BluetoothController";
/**
* Constructor
*
* @param context
*/
public BluetoothController(Context context) {
mContext = context;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
}
/**
* Call this to start BluetoothController functionalities.
*
* @return The return value of startBluetooth()
*/
public boolean start() {
if (!mIsStarted) {
mIsStarted = true;
mIsStarted = startBluetooth();
}
return mIsStarted;
}
/**
* Should call this on onResume or onDestroy.
* Unregister broadcast receivers and stop Sco audio connection
* and cancel count down.
*/
public void stop() {
if (mIsStarted) {
mIsStarted = false;
stopBluetooth();
}
}
/**
* @return true if audio is connected through headset.
*/
public boolean isOnHeadsetSco() {
return mIsOnHeadsetSco;
}
public abstract void onHeadsetDisconnected();
public abstract void onHeadsetConnected();
public abstract void onScoAudioDisconnected();
public abstract void onScoAudioConnected();
/**
* Register for bluetooth headset connection states and Sco audio states.
* Try to connect to bluetooth headset audio by calling startBluetoothSco().
* This is a work around for API < 11 to detect if a headset is connected before
* the application starts.
* <p/>
* The official documentation for startBluetoothSco() states
* <p/>
* "This method can be used by applications wanting to send and received audio to/from
* a bluetooth SCO headset while the phone is not in call."
* <p/>
* Does this mean that startBluetoothSco() would fail if the connected bluetooth device
* is not a headset?
* <p/>
* Thus if a call to startBluetoothSco() is successful, i.e mBroadcastReceiver will receive
* an ACTION_SCO_AUDIO_STATE_CHANGED with intent extra SCO_AUDIO_STATE_CONNECTED, then
* we assume that a headset is connected.
*
* @return false if device does not support bluetooth or current platform does not supports
* use of SCO for off call.
*/
@SuppressWarnings("deprecation")
private boolean startBluetooth() {
Log.d(TAG, "startBluetooth");
// Device support bluetooth
if (mBluetoothAdapter != null) {
if (mAudioManager.isBluetoothScoAvailableOffCall()) {
mContext.registerReceiver(mBroadcastReceiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
mContext.registerReceiver(mBroadcastReceiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
mContext.registerReceiver(mBroadcastReceiver,
new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED));
// Need to set audio mode to MODE_IN_CALL for call to startBluetoothSco() to succeed.
mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
mIsCountDownOn = true;
// mCountDown repeatedly tries to start bluetooth Sco audio connection.
mCountDown.start();
// need for audio sco, see mBroadcastReceiver
mIsStarting = true;
return true;
}
}
return false;
}
/**
* Unregister broadcast receivers and stop Sco audio connection
* and cancel count down.
*/
private void stopBluetooth() {
Log.d(TAG, "stopBluetooth");
if (mIsCountDownOn) {
mIsCountDownOn = false;
mCountDown.cancel();
}
// Need to stop Sco audio connection here when the app
// change orientation or close with headset still turns on.
mContext.unregisterReceiver(mBroadcastReceiver);
mAudioManager.stopBluetoothSco();
mAudioManager.setMode(AudioManager.MODE_NORMAL);
}
/**
* Handle headset and Sco audio connection states.
*/
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@SuppressWarnings({"deprecation", "synthetic-access"})
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {
BluetoothDevice mConnectedHeadset = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BluetoothClass bluetoothClass = mConnectedHeadset.getBluetoothClass();
if (bluetoothClass != null) {
// Check if device is a headset. Besides the 2 below, are there other
// device classes also qualified as headset?
int deviceClass = bluetoothClass.getDeviceClass();
if (deviceClass == BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE
|| deviceClass == BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET) {
// start bluetooth Sco audio connection.
// Calling startBluetoothSco() always returns faIL here,
// that why a count down timer is implemented to call
// startBluetoothSco() in the onTick.
mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
mIsCountDownOn = true;
mCountDown.start();
// override this if you want to do other thing when the device is connected.
onHeadsetConnected();
}
}
Log.d(TAG, mConnectedHeadset.getName() + " connected");
} else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
Log.d(TAG, "Headset disconnected");
if (mIsCountDownOn) {
mIsCountDownOn = false;
mCountDown.cancel();
}
mAudioManager.setMode(AudioManager.MODE_NORMAL);
// override this if you want to do other thing when the device is disconnected.
onHeadsetDisconnected();
} else if (action.equals(AudioManager.ACTION_SCO_AUDIO_STATE_CHANGED)) {
int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE,
AudioManager.SCO_AUDIO_STATE_ERROR);
if (state == AudioManager.SCO_AUDIO_STATE_CONNECTED) {
mIsOnHeadsetSco = true;
if (mIsStarting) {
// When the device is connected before the application starts,
// ACTION_ACL_CONNECTED will not be received, so call onHeadsetConnected here
mIsStarting = false;
onHeadsetConnected();
}
if (mIsCountDownOn) {
mIsCountDownOn = false;
mCountDown.cancel();
}
// override this if you want to do other thing when Sco audio is connected.
onScoAudioConnected();
Log.d(TAG, "Sco connected");
} else if (state == AudioManager.SCO_AUDIO_STATE_DISCONNECTED) {
Log.d(TAG, "Sco disconnected");
// Always receive SCO_AUDIO_STATE_DISCONNECTED on call to startBluetooth()
// which at that stage we do not want to do anything. Thus the if condition.
if (!mIsStarting) {
mIsOnHeadsetSco = false;
// Need to call stopBluetoothSco(), otherwise startBluetoothSco()
// will not be successful.
mAudioManager.stopBluetoothSco();
// override this if you want to do other thing when Sco audio is disconnected.
onScoAudioDisconnected();
}
}
}
}
};
/**
* Try to connect to audio headset in onTick.
*/
private CountDownTimer mCountDown = new CountDownTimer(10000, 1000) {
@SuppressWarnings("synthetic-access")
@Override
public void onTick(long millisUntilFinished) {
// When this call is successful, this count down timer will be canceled.
try {
mAudioManager.startBluetoothSco();
} catch (Exception ignored) {
}
Log.d(TAG, "\nonTick start bluetooth Sco");
}
@SuppressWarnings("synthetic-access")
@Override
public void onFinish() {
// Calls to startBluetoothSco() in onStick are not successful.
// Should implement something to inform user of this failure
mIsCountDownOn = false;
mAudioManager.setMode(AudioManager.MODE_NORMAL);
Log.d(TAG, "\nonFinish fail to connect to headset audio");
}
};
}
|
0
|
java-sources/ai/api/sdk/2.0.7/ai/api
|
java-sources/ai/api/sdk/2.0.7/ai/api/util/RecognizerChecker.java
|
package ai.api.util;
/***********************************************************************************************************************
*
* API.AI Android SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2014 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.ServiceInfo;
import android.os.Build;
import android.speech.RecognitionService;
import java.util.LinkedList;
import java.util.List;
public class RecognizerChecker {
public static final String GOOGLE_RECOGNIZER_PACKAGE_NAME = "com.google.android.googlequicksearchbox";
public static final String GOOGLE_VOICE_SEARCH_PACKAGE_NAME = "com.google.android.voicesearch";
public static ComponentName findGoogleRecognizer(final Context context) {
return findRecognizerByPackage(context, getPackageName());
}
private static ComponentName findRecognizerByPackage(final Context context, final String prefPackage) {
final PackageManager pm = context.getPackageManager();
final List<ResolveInfo> available = pm != null ? pm.queryIntentServices(new Intent(RecognitionService.SERVICE_INTERFACE), 0) : new LinkedList<ResolveInfo>();
final int numAvailable = available.size();
if (numAvailable == 0) {
// no available voice recognition services found
return null;
} else {
if (prefPackage != null) {
for (final ResolveInfo anAvailable : available) {
final ServiceInfo serviceInfo = anAvailable.serviceInfo;
if (serviceInfo != null && prefPackage.equals(serviceInfo.packageName)) {
return new ComponentName(serviceInfo.packageName, serviceInfo.name);
}
}
}
// Do not pick up first available, but use default one
return null;
}
}
public static String getGoogleRecognizerVersion(final Context context) {
try {
final PackageManager pm = context.getPackageManager();
final ComponentName recognizerComponentName = findGoogleRecognizer(context);
if (recognizerComponentName != null) {
final PackageInfo packageInfo = pm.getPackageInfo(recognizerComponentName.getPackageName(), 0);
final String versionName = packageInfo.versionName;
return versionName;
}
return "";
} catch (final PackageManager.NameNotFoundException ignored) {
return "";
}
}
public static boolean isGoogleRecognizerAvailable(final Context context) {
return findGoogleRecognizer(context) != null;
//return false;
}
private static String getPackageName() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
return GOOGLE_RECOGNIZER_PACKAGE_NAME;
} else {
return GOOGLE_VOICE_SEARCH_PACKAGE_NAME;
}
}
}
|
0
|
java-sources/ai/api/sdk/2.0.7/ai/api
|
java-sources/ai/api/sdk/2.0.7/ai/api/util/VersionConfig.java
|
package ai.api.util;
/***********************************************************************************************************************
*
* API.AI Android SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2016 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
* *********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import android.content.Context;
import android.text.TextUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import ai.api.android.GsonFactory;
public class VersionConfig {
private static final String TAG = VersionConfig.class.getName();
private static final Pattern DOT_PATTERN = Pattern.compile(".", Pattern.LITERAL);
private static final Map<String, VersionConfig> configuration = new HashMap<>();
static {
configuration.put("5.9.26", new VersionConfig(true, true));
configuration.put("4.7.13", new VersionConfig(false, false));
}
private boolean destroyRecognizer = true;
private boolean autoStopRecognizer = false;
private VersionConfig() {
}
private VersionConfig(final boolean destroyRecognizer, final boolean autoStopRecognizer) {
this.destroyRecognizer = destroyRecognizer;
this.autoStopRecognizer = autoStopRecognizer;
}
public static VersionConfig init(final Context context) {
return getConfigByVersion(context);
}
private static VersionConfig getConfigByVersion(final Context context) {
final long number = numberFromBuildVersion(RecognizerChecker.getGoogleRecognizerVersion(context));
final VersionConfig config = new VersionConfig();
long prevVersionNumber = 0;
for (final Map.Entry<String, VersionConfig> configEntry : configuration.entrySet()) {
final String versionName = configEntry.getKey();
if (!TextUtils.isEmpty(versionName)) {
final long versionNumber = numberFromBuildVersion(versionName);
if (number >= versionNumber && prevVersionNumber < versionNumber) {
config.destroyRecognizer = configEntry.getValue().destroyRecognizer;
config.autoStopRecognizer = configEntry.getValue().autoStopRecognizer;
prevVersionNumber = versionNumber;
}
}
}
return config;
}
public boolean isDestroyRecognizer() {
return destroyRecognizer;
}
public boolean isAutoStopRecognizer() {
return autoStopRecognizer;
}
private static long numberFromBuildVersion(final String buildVersion) {
if (TextUtils.isEmpty(buildVersion))
return 0;
final String[] parts = DOT_PATTERN.split(buildVersion);
final StringBuilder builder = new StringBuilder();
for (int i = 0; i < Math.min(3, parts.length); i++) {
builder.append(parts[i]);
}
try {
return Long.parseLong(builder.toString());
} catch (final NumberFormatException ignored) {
return 0;
}
}
@Override
public String toString() {
return GsonFactory.getGson().toJson(this);
}
}
|
0
|
java-sources/ai/api/sdk/2.0.7/ai/api
|
java-sources/ai/api/sdk/2.0.7/ai/api/util/VoiceActivityDetector.java
|
package ai.api.util;
/***********************************************************************************************************************
*
* API.AI Android SDK - client-side libraries for API.AI
* =================================================
*
* Copyright (C) 2014 by Speaktoit, Inc. (https://www.speaktoit.com)
* https://www.api.ai
*
***********************************************************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
***********************************************************************************************************************/
import android.util.Log;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
public class VoiceActivityDetector {
public static final String TAG = VoiceActivityDetector.class.getName();
public static final int FRAME_SIZE_IN_BYTES = 320;
private static final int SEQUENCE_LENGTH_MILLIS = 30;
private static final int MIN_SPEECH_SEQUENCE_COUNT = 3;
private static final long MIN_SILENCE_MILLIS = 800;
private static final long MAX_SILENCE_MILLIS = 3500;
private static final long SILENCE_DIFF_MILLIS = MAX_SILENCE_MILLIS - MIN_SILENCE_MILLIS;
private static final int NOISE_FRAMES = 15;
public static final int NOISE_BYTES = NOISE_FRAMES * FRAME_SIZE_IN_BYTES;
private static final double ENERGY_FACTOR = 3.1;
private static final int MIN_CZ = 5;
private static final int MAX_CZ = 15;
private final int sampleRate;
private SpeechEventsListener eventsListener;
private double noiseEnergy = 0.0;
private long lastActiveTime = -1;
/**
* last time active frame hit sequence.
*/
private long lastSequenceTime = 0;
/**
* number of active frame in sequence.
*/
private int sequenceCounter = 0;
/**
* current processed time in millis
*/
private long time = 0;
private int frameNumber;
private long silenceMillis = MAX_SILENCE_MILLIS;
private boolean speechActive = false;
private boolean enabled = true;
private boolean process = true;
private double sum = 0;
private int size = 0;
public VoiceActivityDetector(final int sampleRate) {
this.sampleRate = sampleRate;
}
public void processBuffer(final byte[] buffer, final int bytesRead) {
if (!process) {
return;
}
final ByteBuffer byteBuffer = ByteBuffer.wrap(buffer, 0, bytesRead).order(ByteOrder.LITTLE_ENDIAN);
final ShortBuffer shorts = byteBuffer.asShortBuffer();
final boolean active = isFrameActive(shorts);
final int frameSize = bytesRead / 2; // 16 bit encoding
time = frameNumber * frameSize * 1000 / sampleRate;
if (active) {
if (lastActiveTime >= 0 && (time - lastActiveTime) < SEQUENCE_LENGTH_MILLIS) {
if (++sequenceCounter >= MIN_SPEECH_SEQUENCE_COUNT) {
if (!speechActive) {
onSpeechBegin();
}
lastSequenceTime = time;
silenceMillis = Math.max(MIN_SILENCE_MILLIS, silenceMillis - SILENCE_DIFF_MILLIS / 4);
}
} else {
sequenceCounter = 1;
}
lastActiveTime = time;
} else {
if (time - lastSequenceTime > silenceMillis) {
if (speechActive) {
onSpeechEnd();
} else {
onSpeechCancel();
}
}
}
}
private boolean isFrameActive(final ShortBuffer frame) {
int lastSign = 0;
int czCount = 0;
double energy = 0.0;
final int frameSize = frame.limit();
size += frameSize;
for (int i = 0; i < frameSize; i++) {
final short raw = frame.get(i);
final double amplitude = (double) raw / (double) Short.MAX_VALUE;
energy += (float) amplitude * (float) amplitude / (double) frameSize;
sum += raw * raw;
final int sign = (float) amplitude > 0 ? 1 : -1;
if (lastSign != 0 && sign != lastSign) {
czCount++;
}
lastSign = sign;
}
boolean result = false;
if (++frameNumber < NOISE_FRAMES) {
noiseEnergy += (energy / (double) NOISE_FRAMES);
} else {
if (czCount >= MIN_CZ && czCount <= MAX_CZ) {
if (energy > noiseEnergy * ENERGY_FACTOR) {
result = true;
}
}
}
return result;
}
public double calculateRms() {
final double rms = Math.sqrt(sum / size) / 100;
sum = 0;
size = 0;
return rms;
}
public void reset() {
time = 0;
frameNumber = 0;
noiseEnergy = 0.0;
lastActiveTime = -1;
lastSequenceTime = 0;
sequenceCounter = 0;
silenceMillis = MAX_SILENCE_MILLIS;
speechActive = false;
process = true;
}
public void setSpeechListener(final SpeechEventsListener eventsListener) {
this.eventsListener = eventsListener;
}
private void onSpeechEnd() {
Log.v(TAG, "onSpeechEnd");
speechActive = false;
process = false;
if (enabled) {
if (eventsListener != null) {
eventsListener.onSpeechEnd();
}
}
}
private void onSpeechCancel() {
Log.v(TAG, "onSpeechCancel");
speechActive = false;
process = false;
if (eventsListener != null) {
eventsListener.onSpeechCancel();
}
}
private void onSpeechBegin() {
Log.v(TAG, "onSpeechBegin");
speechActive = true;
if (eventsListener != null) {
eventsListener.onSpeechBegin();
}
}
/**
* If enabled, voice activity detector fires onSpeechEnd events.
* This option does not affect onSpeechBegin and onChangeLevel events
*
* @param enabled new option values
*/
public void setEnabled(final boolean enabled) {
this.enabled = enabled;
}
/**
* Used to notify about speech begin/end events
*/
public interface SpeechEventsListener {
void onSpeechBegin();
void onSpeechCancel();
void onSpeechEnd();
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/ApisuiteApplication.java
|
package ai.apiverse.apisuite;
import ai.apiverse.apisuite.mirror.agent.ApimonitorAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@ImportAutoConfiguration(ApimonitorAutoConfiguration.class)
public class ApisuiteApplication {
public static void main(String[] args) {
SpringApplication.run(ApisuiteApplication.class, args);
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/ApimonitorApiProcessor.java
|
package ai.apiverse.apisuite.mirror.agent;
import ai.apiverse.apisuite.mirror.agent.buffer.ApiBufferKey;
import ai.apiverse.apisuite.mirror.agent.buffer.BufferManagerWorker;
import ai.apiverse.apisuite.mirror.agent.buffer.DiscoveredApiBufferManager;
import ai.apiverse.apisuite.mirror.agent.buffer.RegisteredApiBufferManager;
import ai.apiverse.apisuite.mirror.models.data.APISample;
import lombok.RequiredArgsConstructor;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
@RequiredArgsConstructor
public class ApimonitorApiProcessor {
private final RegisteredApiBufferManager registeredApiBufferManager;
private final DiscoveredApiBufferManager discoveredApiBufferManager;
private final List<String> maskHeaders;
private final SDKLogger logger;
private static ContentCachingRequestWrapper wrapRequest(HttpServletRequest request) {
if (request instanceof ContentCachingRequestWrapper) {
return (ContentCachingRequestWrapper) request;
} else {
return new ContentCachingRequestWrapper(request);
}
}
private static ContentCachingResponseWrapper wrapResponse(HttpServletResponse response) {
if (response instanceof ContentCachingResponseWrapper) {
return (ContentCachingResponseWrapper) response;
} else {
return new ContentCachingResponseWrapper(response);
}
}
public void processDiscoveredApi(ApimonitorSpringFilter.RequestResponseContext context, final FilterChain filterChain) throws ServletException, IOException {
BufferManagerWorker<ApiBufferKey> worker = this.discoveredApiBufferManager.getWorker();
if (null == worker) {
logger.error("BufferManagerWorker is NULL inside RegisteredApiProcessor");
doFilter(filterChain, context);
return;
}
boolean canOffer = worker.canOffer(context.getApiBufferKey());
context.setPayloadCaptureAttempted(false);
try {
doFilter(filterChain, context);
} catch (Exception exception) {
if (canOffer) {
tryOffering(context, exception, worker);
}
throw exception;
}
if (canOffer) {
tryOffering(context, null, worker);
}
}
public void processRegisteredApi(ApimonitorSpringFilter.RequestResponseContext context, final FilterChain filterChain) throws ServletException, IOException {
BufferManagerWorker<ApiBufferKey> worker = this.registeredApiBufferManager.getWorker();
if (null == worker) {
logger.error("BufferManagerWorker is NULL inside RegisteredApiProcessor");
doFilter(filterChain, context);
return;
}
boolean canOffer = worker.canOffer(context.getApiBufferKey());
context.setPayloadCaptureAttempted(true);
boolean requestPayloadCaptureAttempted = false;
boolean responsePayloadCaptureAttempted = false;
if (canOffer) {
requestPayloadCaptureAttempted = shouldCaptureRequest(context);
if (requestPayloadCaptureAttempted) {
context.setCachedRequest(wrapRequest(context.getServletRequest()));
}
responsePayloadCaptureAttempted = shouldCaptureResponse(context);
if (responsePayloadCaptureAttempted) {
context.setCachedResponse(wrapResponse(context.getServletResponse()));
}
context.setRequestPayloadCaptureAttempted(requestPayloadCaptureAttempted);
context.setResponsePayloadCaptureAttempted(responsePayloadCaptureAttempted);
}
try {
long startTime = 0;
boolean shouldComputeLatency = canOffer;
if (shouldComputeLatency) {
startTime = System.currentTimeMillis();
}
doFilter(filterChain, context);
if (shouldComputeLatency) {
context.setLatency(System.currentTimeMillis() - startTime);
}
} catch (Exception exception) {
if (canOffer) {
tryOffering(context, exception, worker);
}
throw exception;
}
if (canOffer) {
tryOffering(context, null, worker);
}
}
private void tryOffering(ApimonitorSpringFilter.RequestResponseContext context, Exception exception, BufferManagerWorker<ApiBufferKey> worker) {
try {
APISample apiSample = getBufferEntryForApiSample(context, exception);
if (null != apiSample) {
worker.offer(context.getApiBufferKey(), apiSample);
}
} catch (Exception e) {
}
}
private void doFilter(final FilterChain filterChain, ApimonitorSpringFilter.RequestResponseContext context) throws ServletException, IOException {
final HttpServletRequest servletRequest = null != context.getCachedRequest() ? context.getCachedRequest() : context.getServletRequest();
final HttpServletResponse servletResponse = null != context.getCachedResponse() ? context.getCachedResponse() : context.getServletResponse();
filterChain.doFilter(servletRequest, servletResponse);
}
private boolean shouldCaptureRequest(ApimonitorSpringFilter.RequestResponseContext context) {
if (null != context.getApiConfig() && null != context.getApiConfig().getCaptureSampleRequest() && !context.getApiConfig().getCaptureSampleRequest()) {
return false;
}
return true;
}
private boolean shouldCaptureResponse(ApimonitorSpringFilter.RequestResponseContext context) {
if (null != context.getApiConfig() && null != context.getApiConfig().getCaptureSampleResponse() && !context.getApiConfig().getCaptureSampleResponse()) {
return false;
}
return true;
}
private APISample getBufferEntryForApiSample(ApimonitorSpringFilter.RequestResponseContext context, Exception exception) {
APISample apiSample = new APISample();
apiSample.setApplicationName(context.getApplicationName());
try {
if (null != context.getApiConfig()) {
apiSample.setMethod(context.getApiConfig().getMethod());
} else {
apiSample.setMethod(context.getObservedApi().getMethod());
}
apiSample.setRawUri(context.getObservedApi().getUri().getUriPath());
apiSample.setUri(context.getObservedApi().getUri());
apiSample.setParameters(getParameters(context.getServletRequest()));
apiSample.setRequestHeaders(MaskingUtils.getReplacedHeaders(getRequestHeaders(context), maskHeaders));
apiSample.setResponseHeaders(MaskingUtils.getReplacedHeaders(getResponseHeaders(context), maskHeaders));
apiSample.setLatency(context.getLatency());
apiSample.setHostName(context.getServletRequest().getServerName());
apiSample.setPort(context.getServletRequest().getServerPort());
apiSample.setScheme(context.getServletRequest().getScheme());
if (null != context.getCachedRequest()) {
apiSample.setRequestPayload(new String(context.getCachedRequest().getContentAsByteArray()));
}
apiSample.setStatusCode(context.getServletResponse().getStatus());
if (null == exception) {
if (null != context.getCachedResponse()) {
apiSample.setResponsePayload(new String(context.getCachedResponse().getContentAsByteArray()));
context.getCachedResponse().copyBodyToResponse();
apiSample.setStatusCode(context.getCachedResponse().getStatus());
}
} else {
// this is uncaught exception, even after all exception mappers
apiSample.setUncaughtExceptionMessage(exception.getCause().getMessage());
apiSample.setStatusCode(500);
}
apiSample.setRequestPayloadCaptureAttempted(context.getRequestPayloadCaptureAttempted());
apiSample.setResponsePayloadCaptureAttempted(context.getResponsePayloadCaptureAttempted());
apiSample.setPayloadCaptureAttempted(context.getPayloadCaptureAttempted());
} catch (Exception e) {
logger.error("Error create bufferEntry for API", e);
}
return apiSample;
}
private Map<String, String> getRequestHeaders(ApimonitorSpringFilter.RequestResponseContext context) {
HttpServletRequest httpServletRequest = null;
if (null != context.getCachedRequest()) {
httpServletRequest = context.getCachedRequest();
} else {
httpServletRequest = context.getServletRequest();
}
if (null == httpServletRequest) {
return new HashMap<>();
}
Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
Map<String, String> headerMap = new HashMap<>();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
headerMap.put(headerName, httpServletRequest.getHeader(headerName));
}
}
return headerMap;
}
private Map<String, String> getResponseHeaders(ApimonitorSpringFilter.RequestResponseContext context) {
HttpServletResponse httpServletResponse = null;
if (null != context.getCachedResponse()) {
httpServletResponse = context.getCachedResponse();
} else {
httpServletResponse = context.getServletResponse();
}
if (null == httpServletResponse || null == httpServletResponse.getHeaderNames()) {
return new HashMap<>();
}
Collection<String> headerNames = httpServletResponse.getHeaderNames();
Map<String, String> headerMap = new HashMap<>();
for (String header : headerNames) {
headerMap.put(header, httpServletResponse.getHeader(header));
}
headerMap.put("Content-Type", httpServletResponse.getContentType());
return headerMap;
}
private Map<String, String[]> getParameters(HttpServletRequest servletRequest) {
Map<String, String[]> servletParameterMap = servletRequest.getParameterMap();
Map<String, String[]> parameterMap = new HashMap<>();
for (String key : servletParameterMap.keySet()) {
parameterMap.put(key, servletParameterMap.get(key));
}
return parameterMap;
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/ApimonitorAutoConfiguration.java
|
package ai.apiverse.apisuite.mirror.agent;
import ai.apiverse.apisuite.mirror.agent.buffer.Constants;
import ai.apiverse.apisuite.mirror.agent.buffer.DiscoveredApiBufferManager;
import ai.apiverse.apisuite.mirror.agent.buffer.RegisteredApiBufferManager;
import ai.apiverse.apisuite.mirror.agent.config.ConfigManager;
import ai.apiverse.apisuite.mirror.agent.config.SimpleConfigManager;
import ai.apiverse.apisuite.mirror.models.data.ApiOwner;
import ai.apiverse.apisuite.scanner.ApiScannerConfig;
import ai.apiverse.apisuite.scanner.EndpointService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.event.EventListener;
import org.springframework.web.filter.OncePerRequestFilter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(name = "apimonitor.enabled", havingValue = "true")
@Import(ApimonitorHttpConnectionConfig.class)
public class ApimonitorAutoConfiguration implements ApplicationContextAware {
private ApplicationContext apiPulseContext;
@Value("${apimonitor.url:}")
private String url;
@Value("${apimonitor.applicationName:}")
private String userApplicationName;
@Value("${apimonitor.loggingEnabled:false}")
private boolean loggingEnabled;
@Value("${apimonitor.logLevel:ERROR}")
private String logLevel;
@Value("${apimonitor.authKey:}")
private String authKey;
@Value("${apimonitor.environment:}")
private String environment;
@Value("${apimonitor.team:}")
private String team;
@Value("${apimonitor.apikey:}")
private String apiKey;
@Value("${apimonitor.accountid:}")
private String accountId;
@Value("${apimonitor.maskHeaders:}")
private List<String> maskHeaders;
@Bean
@Qualifier("apimonitor-filter")
@ConditionalOnProperty(prefix = "apimonitor", name = {"url"})
OncePerRequestFilter getapimonitorSpringFilter(ApimonitorHttpConnectionConfig apimonitorHttpConnectionConfig) {
SDKLogger.LogLevel logLevel = null == this.logLevel ? SDKLogger.LogLevel.ERROR : SDKLogger.LogLevel.valueOf(this.logLevel);
SDKLogger sdkLogger = new SDKLogger(loggingEnabled, logLevel);
if (null == url || url.length() == 0) {
String message = "Mandatory Config `apimonitor.url` is missing";
System.out.println(message);
sdkLogger.forceLog(message);
return new ApimonitorNoOpFilter();
}
if (null == userApplicationName || userApplicationName.length() == 0) {
String message = "Mandatory Config `apimonitor.applicationName` is missing";
System.out.println(message);
sdkLogger.forceLog(message);
return new ApimonitorNoOpFilter();
}
url = url.trim();
userApplicationName = userApplicationName.trim();
Random random = new Random();
int randomId = random.nextInt(1000);
String agentId = String.valueOf(randomId);
ApiOwner apiOwner = new ApiOwner();
apiOwner.setEnv(environment);
apiOwner.setTeam(team);
apiOwner.setServiceName(userApplicationName);
Map<String, String> accessHeaders = getAccessHeaders();
ApimonitorHTTPConnection apimonitorHTTPConnection = new ApimonitorHTTPConnection(url, userApplicationName, agentId, apimonitorHttpConnectionConfig, sdkLogger, authKey, environment, apiOwner, accessHeaders);
ConfigManager configManager = new SimpleConfigManager(url, userApplicationName, agentId, apimonitorHTTPConnection, sdkLogger);
configManager.init();
RegisteredApiBufferManager registeredApiBufferManager = new RegisteredApiBufferManager(configManager, apimonitorHTTPConnection, url, sdkLogger);
registeredApiBufferManager.init();
DiscoveredApiBufferManager discoveredApiBufferManager = new DiscoveredApiBufferManager(configManager, apimonitorHTTPConnection, url, sdkLogger);
discoveredApiBufferManager.init();
ApimonitorApiProcessor apimonitorApiProcessor = new ApimonitorApiProcessor(registeredApiBufferManager, discoveredApiBufferManager, maskHeaders, sdkLogger);
ApimonitorSpringFilter apimonitorSpringFilter = new ApimonitorSpringFilter(configManager, apimonitorApiProcessor, userApplicationName, sdkLogger);
apimonitorSpringFilter.init();
String message = String.format("apimonitor Initialised!\napplicationName:: %s\nurl:: %s\nagentId:: %s\nSDK Version:: %s.%s\nHeader mask keys:: %s",
userApplicationName, url, agentId, SDKVersion.MAJOR_VERSION, SDKVersion.MINOR_VERSION, String.join(", ", maskHeaders));
System.out.println(message);
sdkLogger.forceLog(message);
return apimonitorSpringFilter;
}
private Map<String, String> getAccessHeaders() {
Map<String,String> accessHeaders = new HashMap<>();
accessHeaders.put(Constants.PARTNER_ID_HEADER, accountId);
accessHeaders.put(Constants.API_KEY_HEADER, apiKey);
accessHeaders.put(Constants.TEAM_NAME_HEADER,team);
accessHeaders.put(Constants.SERVICE_NAME_HEADER,userApplicationName);
accessHeaders.put(Constants.ENV_NAME_HEADER,environment);
return accessHeaders;
}
@EventListener(ApplicationStartedEvent.class)
public void initscan() {
try {
EndpointService endpointService = new EndpointService();
endpointService.setApplicationContext(this.apiPulseContext);
ApiScannerConfig apiScannerConfig = ApiScannerConfig.getInstance();
apiScannerConfig.setEndpointService(endpointService);
apiScannerConfig.setLogEnable(loggingEnabled);
apiScannerConfig.printLog("maintaining api inventory", "");
apiScannerConfig.setApiFlowBackendUrl(url);
apiScannerConfig.setUserApplicationName(userApplicationName);
Map<String, String> accessHeaders = getAccessHeaders();
apiScannerConfig.setAccessHeaders(accessHeaders);
apiScannerConfig.postApiInfoToInventory();
} catch (Exception e) {
ApiScannerConfig apiScannerConfig = ApiScannerConfig.getInstance();
apiScannerConfig.printLog("exception occured while trying to maintain api inventory", e.getMessage());
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.apiPulseContext = applicationContext;
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/ApimonitorHTTPConnection.java
|
package ai.apiverse.apisuite.mirror.agent;
import ai.apiverse.apisuite.mirror.agent.buffer.Constants;
import ai.apiverse.apisuite.mirror.models.data.APISample;
import ai.apiverse.apisuite.mirror.models.data.AgentConfig;
import ai.apiverse.apisuite.mirror.models.data.ApiOwner;
import ai.apiverse.apisuite.mirror.models.data.ApiSampleWrapper;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.util.ObjectUtils;
import org.springframework.web.util.UriComponentsBuilder;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.net.HttpURLConnection.HTTP_OK;
public final class ApimonitorHTTPConnection {
@SuppressWarnings("CharsetObjectCanBeUsed")
private static final Charset UTF_8 = Charset.forName("UTF-8");
final String userApplicationName;
final String agentId;
final ApiOwner apiOwner;
private final Map<String, String> headers;
private final ApimonitorHttpConnectionConfig httpConnectionConfig;
private final SDKLogger sdkLogger;
private final ObjectMapper objectMapper;
private URL apimonitorSendSampleUrl = null;
private URL apimonitorConfigUrl = null;
public ApimonitorHTTPConnection(String apimonitorUrl,
final String userApplicationName,
final String agentId,
ApimonitorHttpConnectionConfig apimonitorHttpConnectionConfig,
SDKLogger sdkLogger,
String authKey,
String environment, ApiOwner apiOwner, Map<String, String> accessHeaders) {
this.userApplicationName = userApplicationName;
this.agentId = agentId;
this.sdkLogger = sdkLogger;
this.apiOwner = apiOwner;
headers = new HashMap<>();
headers.put(SDKVersion.MAJOR_VERSION_KEY, SDKVersion.MAJOR_VERSION);
headers.put(SDKVersion.MINOR_VERSION_KEY, SDKVersion.MINOR_VERSION);
for (Map.Entry<String, String> entry : accessHeaders.entrySet()) {
headers.put(entry.getKey(), entry.getValue());
}
if (authKey != null) {
headers.put("authKey", authKey);
}
if (environment != null) {
headers.put("environment", environment);
}
this.httpConnectionConfig = apimonitorHttpConnectionConfig;
this.objectMapper = getObjectMapper();
try {
apimonitorSendSampleUrl = URI.create(apimonitorUrl + Constants.SAMPLE_INGESTION_URI).toURL();
} catch (Exception e) {
String message = String.format("Unable to create SendSampleUrl from %s. Error: %s", apimonitorUrl, e.getMessage());
System.out.println(message);
sdkLogger.forceLog(message);
}
try {
Map<String, String> queryParams = new HashMap<>();
queryParams.put("appName", userApplicationName);
queryParams.put("agentId", agentId);
String configUrl = apimonitorUrl + Constants.CONFIG_URI + getQueryParams(queryParams);
apimonitorConfigUrl = URI.create(configUrl).toURL();
} catch (Exception e) {
String message = String.format("Unable to create ConfigUrl from %s. Error: %s", apimonitorUrl, e.getMessage());
System.out.println(message);
sdkLogger.forceLog(message);
}
}
private static String getQueryParams(Map<String, String> params) throws UnsupportedEncodingException {
if (ObjectUtils.isEmpty(params)) {
return "";
}
UriComponentsBuilder componentsBuilder = UriComponentsBuilder.newInstance();
for (Map.Entry<String, String> entry : params.entrySet()) {
componentsBuilder.queryParam(entry.getKey(), URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString()));
}
return componentsBuilder.
build().
toString();
}
private ObjectMapper getObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
// Register a simple deserializer for java.net.URI
module.addDeserializer(URI.class, new StdDeserializer<URI>(URI.class) {
@Override
public URI deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
return URI.create(p.getText());
}
});
objectMapper.registerModule(module);
return objectMapper;
}
public void sendSamples(List<APISample> dataList) {
try {
if (null == apimonitorSendSampleUrl) {
this.sdkLogger.error("SendSampleUrl is null");
return;
}
if (null == dataList || dataList.size() == 0) {
this.sdkLogger.error("No Samples to send");
return;
}
ApiSampleWrapper apiSampleWrapper = new ApiSampleWrapper();
apiSampleWrapper.setApiSamples(dataList);
apiSampleWrapper.setApiOwner(this.apiOwner);
String payload = null;
try {
payload = objectMapper.writeValueAsString(apiSampleWrapper);
} catch (Exception e) {
this.sdkLogger.error("Error while parsing content", e);
return;
}
if (null == payload || payload.length() == 0) {
this.sdkLogger.error("Content is empty");
return;
}
HttpURLConnection connection = (HttpURLConnection) apimonitorSendSampleUrl.openConnection();
for (Map.Entry<String, String> header : headers.entrySet()) {
connection.setRequestProperty(header.getKey(), header.getValue());
}
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Connection", "close");
connection.setConnectTimeout(httpConnectionConfig.getConnectTimeout());
connection.setReadTimeout(httpConnectionConfig.getReadTimeout());
connection.connect();
try (final OutputStream outputStream = connection.getOutputStream()) {
try (final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
final Writer writer =
new BufferedWriter(new OutputStreamWriter(bufferedOutputStream, UTF_8))) {
writer.write(payload);
writer.flush();
}
} catch (Throwable e) {
this.sdkLogger.error("An exception occurred while sending Samples", e);
} finally {
try {
final int responseCode = connection.getResponseCode();
if (!isSuccessfulResponseCode(responseCode)) {
this.sdkLogger.error(String.format("Send Sample Request failed, API returned %s", responseCode));
if (this.sdkLogger.canLogError()) {
String errorMessage = getErrorMessageFromStream(connection);
this.sdkLogger.error(errorMessage);
}
}
} catch (Exception e) {
this.sdkLogger.error("Error reading and logging the response stream", e);
} finally {
closeAndDisconnect(connection);
}
}
} catch (Exception e) {
sdkLogger.error("Error apimonitorHTTPConnection::sendSamples", e);
}
}
public AgentConfig getSDKConfig() {
try {
if (null == apimonitorConfigUrl) {
this.sdkLogger.error("SendSampleUrl is null");
return null;
}
HttpURLConnection connection = (HttpURLConnection) apimonitorConfigUrl.openConnection();
for (Map.Entry<String, String> header : headers.entrySet()) {
connection.setRequestProperty(header.getKey(), header.getValue());
}
connection.setRequestMethod("GET");
connection.setDoOutput(false);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Connection", "close");
connection.setConnectTimeout(httpConnectionConfig.getConnectTimeout());
connection.setReadTimeout(httpConnectionConfig.getReadTimeout());
connection.connect();
try {
final int responseCode = connection.getResponseCode();
if (!isSuccessfulResponseCode(responseCode)) {
this.sdkLogger.error(String.format("GetConfig Request failed, API returned %s", responseCode));
if (this.sdkLogger.canLogError()) {
String errorMessage = getErrorMessageFromStream(connection);
this.sdkLogger.error(errorMessage);
}
return null;
} else {
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), UTF_8))) {
StringBuilder responseBuilder = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
responseBuilder.append(responseLine.trim());
}
String response = responseBuilder.toString();
if (response.length() == 0) {
return null;
} else {
return objectMapper.readValue(response, new TypeReference<AgentConfig>() {
});
}
}
}
} catch (Exception e) {
this.sdkLogger.error("Error reading and logging the response stream", e);
} finally {
closeAndDisconnect(connection);
}
} catch (Exception e) {
sdkLogger.error("Error apimonitorHTTPConnection::getAgentConfig", e);
}
return null;
}
/**
* Closes the Response stream and disconnect the connection
*
* @param connection the HttpURLConnection
*/
private void closeAndDisconnect(final HttpURLConnection connection) {
try {
connection.getInputStream().close();
} catch (IOException ignored) {
// connection is already closed
} finally {
connection.disconnect();
}
}
/**
* Reads the error message from the error stream
*
* @param connection the HttpURLConnection
* @return the error message or null if none
*/
private String getErrorMessageFromStream(final HttpURLConnection connection) {
try (final InputStream errorStream = connection.getErrorStream();
final BufferedReader reader =
new BufferedReader(new InputStreamReader(errorStream, UTF_8))) {
final StringBuilder sb = new StringBuilder();
String line;
// ensure we do not add "\n" to the last line
boolean first = true;
while ((line = reader.readLine()) != null) {
if (!first) {
sb.append("\n");
}
sb.append(line);
first = false;
}
return sb.toString();
} catch (IOException e) {
return "Failed to obtain error message while analyzing send failure.";
}
}
/**
* Returns if response code is OK=200
*
* @param responseCode the response code
* @return true if it is OK=200 or false otherwise
*/
private boolean isSuccessfulResponseCode(final int responseCode) {
return responseCode == HTTP_OK;
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/ApimonitorHttpConnectionConfig.java
|
package ai.apiverse.apisuite.mirror.agent;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Getter
@Setter
@Configuration
public class ApimonitorHttpConnectionConfig {
@Value("#{new Integer('${apimonitor.http.maxTotalConnections:3}')}")
private Integer maxConnTotal;
@Value("#{new Integer('${apimonitor.http.socketTimeoutMs:6000}')}")
private Integer socketTimeout;
@Value("#{new Integer('${apimonitor.http.connectTimeoutMs:6000}')}")
private Integer connectTimeout;
@Value("#{new Integer('${apimonitor.http.readTimeout:6000}')}")
private Integer readTimeout;
@Value("#{new Integer('${apimonitor.http.connectionRequestTimeoutMs:6000}')}")
private Integer connectionRequestTimeout;
@Value("#{new Integer('${apimonitor.http.maxSingleRouteConnections:3}')}")
private Integer maxConnPerRoute;
@Value("#{new Integer('${apimonitor.http.idleConnectionWaitTimeMs:30000}')}")
private Integer idleConnectionWaitTime;
@Value("#{new Integer('${apimonitor.http.defaultKeepAliveTimeMs:30000}')}")
private Integer defaultKeepAliveTime;
@Value("#{new Integer('${apimonitor.http.maxRetries:3}')}")
private int retryCount;
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/ApimonitorNoOpFilter.java
|
package ai.apiverse.apisuite.mirror.agent;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Order
public class ApimonitorNoOpFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
filterChain.doFilter(request, response);
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/ApimonitorSpringFilter.java
|
package ai.apiverse.apisuite.mirror.agent;
import ai.apiverse.apisuite.mirror.agent.buffer.ApiBufferKey;
import ai.apiverse.apisuite.mirror.agent.commons.ObservedApi;
import ai.apiverse.apisuite.mirror.agent.config.ConfigManager;
import ai.apiverse.apisuite.mirror.agent.config.ConfigUpdateListener;
import ai.apiverse.apisuite.mirror.models.constant.HttpRequestMethod;
import ai.apiverse.apisuite.mirror.models.data.AgentConfig;
import ai.apiverse.apisuite.mirror.models.data.BlackListRule;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.experimental.FieldDefaults;
import lombok.extern.log4j.Log4j2;
import org.springframework.core.annotation.Order;
import org.springframework.util.CollectionUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@Order
@Log4j2
public class ApimonitorSpringFilter extends OncePerRequestFilter implements ConfigUpdateListener {
private AgentConfig agentConfig;
private ConfigManager configManager;
private ApimonitorApiProcessor apiProcessor;
private String userApplicationName;
private SDKLogger logger;
public ApimonitorSpringFilter(ConfigManager configManager, ApimonitorApiProcessor apiProcessor, String userApplicationName, SDKLogger logger) {
this.configManager = configManager;
this.apiProcessor = apiProcessor;
this.userApplicationName = userApplicationName;
this.logger = logger;
}
public boolean init() {
logger.info("filter initalised");
configManager.subscribeToUpdates(this);
return true;
}
@Override
protected void doFilterInternal(
final HttpServletRequest servletRequest,
final HttpServletResponse servletResponse,
final FilterChain filterChain)
throws ServletException, IOException {
AgentConfig agentConfigLocal = this.agentConfig;
if (null == agentConfigLocal) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}
if (null == agentConfigLocal.getCaptureApiSample() ||
!agentConfigLocal.getCaptureApiSample()) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}
ObservedApi observedApi = getObservedApiFromRequest(servletRequest);
if (isBlackListedApi(observedApi, agentConfigLocal)) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}
RequestResponseContext context = new RequestResponseContext(servletRequest, servletResponse,
userApplicationName);
context.setObservedApi(observedApi);
AgentConfig.ApiConfig apiConfig = getApiConfig(observedApi, agentConfigLocal);
context.setAgentConfig(agentConfigLocal);
if (null != apiConfig) {
context.setApiConfig(apiConfig);
context.setApiBufferKey(ApiBufferKey.getApiBufferKeyFrom(context.getApiConfig()));
apiProcessor.processRegisteredApi(context, filterChain);
} else {
context.setApiBufferKey(ApiBufferKey.getApiBufferKeyFrom(context.getObservedApi()));
apiProcessor.processDiscoveredApi(context, filterChain);
}
}
private boolean isBlackListedApi(ObservedApi observedApi, AgentConfig agentConfig) {
try {
if (null == agentConfig || null == agentConfig.getBlackListRules()) {
return false;
}
for (BlackListRule blackListRule : agentConfig.getBlackListRules()) {
if (blackListRule.matchesUri(observedApi.getUri(), observedApi.getMethod())) {
return true;
}
}
} catch (Exception e) {
logger.error("Error ApimonitorSpringFilter::isBlackListedApi", e);
}
return false;
}
private AgentConfig.ApiConfig getApiConfig(ObservedApi observedApi, AgentConfig agentConfig) {
if (CollectionUtils.isEmpty(agentConfig.getRegisteredApiConfigs())) {
return null;
}
List<AgentConfig.ApiConfig> registeredApis = agentConfig.getRegisteredApiConfigs();
for (AgentConfig.ApiConfig apiConfig : registeredApis) {
if (observedApi.matches(apiConfig)) {
return apiConfig;
}
}
return null;
}
private ObservedApi getObservedApiFromRequest(HttpServletRequest servletRequest) {
return new ObservedApi(servletRequest.getRequestURI(), HttpRequestMethod.valueOf(servletRequest.getMethod()));
}
@Override
public void onSuccessfulConfigUpdate(AgentConfig agentConfig) {
this.agentConfig = agentConfig;
}
@Override
public void onErroneousConfigUpdate() {
this.agentConfig = AgentConfig.noOpAgentConfig;
}
@Getter
@Setter
@RequiredArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
public static class RequestResponseContext {
final HttpServletRequest servletRequest;
final HttpServletResponse servletResponse;
final String applicationName;
ContentCachingRequestWrapper cachedRequest;
ContentCachingResponseWrapper cachedResponse;
ObservedApi observedApi;
AgentConfig.ApiConfig apiConfig;
AgentConfig agentConfig;
ApiBufferKey apiBufferKey;
Boolean payloadCaptureAttempted;
Boolean requestPayloadCaptureAttempted;
Boolean responsePayloadCaptureAttempted;
Long latency;
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/HttpException.java
|
package ai.apiverse.apisuite.mirror.agent;
public class HttpException extends Exception {
public HttpException(String message) {
super(message);
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/HttpRequest.java
|
package ai.apiverse.apisuite.mirror.agent;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.FieldDefaults;
import java.util.Map;
@Getter
@Setter
@FieldDefaults(level = AccessLevel.PRIVATE)
@AllArgsConstructor
public class HttpRequest<IN, OUT> {
String url;
IN requestBody;
Map<String, String> queryParams;
Map<String, String> requestHeaders;
TypeReference<OUT> responseType;
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/MaskingUtils.java
|
package ai.apiverse.apisuite.mirror.agent;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
public class MaskingUtils {
public static Map<String, String> getReplacedHeaders(Map<String, String> headerMap, List<String> maskHeaders) {
if (headerMap == null || maskHeaders == null || maskHeaders.size() == 0) return headerMap;
Set<String> headerNames = headerMap.keySet();
headerNames.forEach(headerName -> {
Optional<String> foundHeader = maskHeaders.stream()
.filter(hn -> hn.equalsIgnoreCase(headerName))
.findAny();
if (foundHeader.isPresent()) {
headerMap.put(headerName, "\uD83D\uDD12MASKED\uD83D\uDD12");
}
});
return headerMap;
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/SDKLogger.java
|
package ai.apiverse.apisuite.mirror.agent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class SDKLogger {
boolean loggingEnabled;
LogLevel logLevel;
Log logger;
public SDKLogger(boolean loggingEnabled, LogLevel logLevel) {
this.loggingEnabled = loggingEnabled;
this.logLevel = logLevel;
logger = LogFactory.getLog(SDKLogger.class);
}
public void info(Object object) {
if (loggingEnabled && logLevel == LogLevel.INFO && null != logger) {
logger.info(object);
}
}
public void forceLog(Object object) {
if (null != logger) {
logger.info(object);
}
}
public void info(Object object, Throwable throwable) {
if (loggingEnabled && logLevel == LogLevel.INFO && null != logger) {
logger.info(object, throwable);
}
}
public boolean canLogError() {
return loggingEnabled && (logLevel == LogLevel.INFO || logLevel == LogLevel.ERROR) && null != logger;
}
public void error(Object object) {
if (canLogError()) {
logger.error(object);
}
}
public void error(Object object, Throwable throwable) {
if (canLogError()) {
logger.error(object, throwable);
}
}
public enum LogLevel {
INFO,
ERROR
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/SDKVersion.java
|
package ai.apiverse.apisuite.mirror.agent;
public class SDKVersion {
public static final String MAJOR_VERSION_KEY = "sdk_major";
public static final String MINOR_VERSION_KEY = "sdk_minor";
public static final String MAJOR_VERSION = "1";
public static final String MINOR_VERSION = "3";
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/buffer/AbstractBufferManager.java
|
package ai.apiverse.apisuite.mirror.agent.buffer;
import ai.apiverse.apisuite.mirror.agent.SDKLogger;
import ai.apiverse.apisuite.mirror.agent.config.ConfigManager;
import ai.apiverse.apisuite.mirror.agent.config.ConfigUpdateListener;
import ai.apiverse.apisuite.mirror.models.data.AgentConfig;
public abstract class AbstractBufferManager implements ConfigUpdateListener {
private final ConfigManager configManager;
private BufferManagerWorker<ApiBufferKey> dummyWorker;
// SimpleBufferManagerWorker is an immutable object. So we are not using any synchronization to publish.
private BufferManagerWorker<ApiBufferKey> worker;
public AbstractBufferManager(ConfigManager configManager, SDKLogger logger) {
this.configManager = configManager;
dummyWorker = new NoOpBufferManagerWorker<ApiBufferKey>(logger);
this.worker = dummyWorker;
}
public BufferManagerWorker<ApiBufferKey> getWorker() {
return this.worker;
}
abstract BufferManagerWorker<ApiBufferKey> createWorker(AgentConfig newConfig);
public synchronized void onSuccessfulConfigUpdate(AgentConfig newAgentConfig) {
if (isRefreshNeeded(worker.getOperatingConfig(), newAgentConfig)) {
BufferManagerWorker<ApiBufferKey> oldBufferManagerWorker = worker;
worker = createWorker(newAgentConfig);
oldBufferManagerWorker.shutdown();
}
}
public synchronized void onErroneousConfigUpdate() {
BufferManagerWorker<ApiBufferKey> oldBuffer = worker;
worker = dummyWorker;
oldBuffer.shutdown();
}
public boolean init() {
return configManager.subscribeToUpdates(this);
}
public boolean shutdown() {
if (worker != null) {
worker.shutdown();
worker = null;
}
return true;
}
private boolean isRefreshNeeded(AgentConfig olderConfig, AgentConfig newConfig) {
if (newConfig.getTimestamp().getTime() == 0 && olderConfig.getTimestamp().getTime() == 0) {
return false;
}
return newConfig.getTimestamp().getTime() > olderConfig.getTimestamp().getTime();
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/buffer/ApiBufferKey.java
|
package ai.apiverse.apisuite.mirror.agent.buffer;
import ai.apiverse.apisuite.mirror.agent.commons.ObservedApi;
import ai.apiverse.apisuite.mirror.models.constant.HttpRequestMethod;
import ai.apiverse.apisuite.mirror.models.data.AgentConfig;
import ai.apiverse.apisuite.mirror.models.data.URI;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.experimental.FieldDefaults;
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
@RequiredArgsConstructor
@Getter
@Setter
public class ApiBufferKey {
URI uri;
HttpRequestMethod method;
public static ApiBufferKey getApiBufferKeyFrom(ObservedApi observedApi) {
return new ApiBufferKey(observedApi.getUri(), observedApi.getMethod());
}
public static ApiBufferKey getApiBufferKeyFrom(AgentConfig.ApiConfig apiConfig) {
return new ApiBufferKey(apiConfig.getUri(), apiConfig.getMethod());
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null) {
return false;
}
// type check and cast
if (getClass() != object.getClass()) {
return false;
}
ApiBufferKey other = (ApiBufferKey) object;
return this.method.equals(other.getMethod()) && this.uri.equals(other.getUri());
}
@Override
public int hashCode() {
final int PRIME = 59;
int result = 1;
result = result * PRIME + this.uri.hashCode();
result = result * PRIME + this.method.hashCode();
return result;
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/buffer/Buffer.java
|
package ai.apiverse.apisuite.mirror.agent.buffer;
import ai.apiverse.apisuite.mirror.models.data.APISample;
public interface Buffer {
boolean offer(APISample e);
boolean canOffer();
APISample poll();
boolean clear();
int getContentCount();
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/buffer/BufferManagerWorker.java
|
package ai.apiverse.apisuite.mirror.agent.buffer;
import ai.apiverse.apisuite.mirror.agent.SDKLogger;
import ai.apiverse.apisuite.mirror.models.data.APISample;
import ai.apiverse.apisuite.mirror.models.data.AgentConfig;
import lombok.NonNull;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
import java.util.Set;
import java.util.concurrent.*;
public abstract class BufferManagerWorker<K> {
protected final ConcurrentMap<ApiBufferKey, Buffer> bufferMap = new ConcurrentHashMap<>();
protected final SDKLogger logger;
private final ScheduledExecutorService bufferSyncExecutorService = Executors.newSingleThreadScheduledExecutor(new CustomizableThreadFactory("buffer-"));
private final AgentConfig config;
;
private final String ctUrl;
public BufferManagerWorker(@NonNull AgentConfig config, String ctUrl, SDKLogger logger) {
this.config = config;
this.ctUrl = ctUrl;
this.logger = logger;
Runnable runnable = this::syncForKeys;
bufferSyncExecutorService.scheduleWithFixedDelay(runnable,
config.getBufferSyncFreqInSec(),
config.getBufferSyncFreqInSec(),
TimeUnit.SECONDS);
}
public BufferManagerWorker(SDKLogger logger) {
this.config = null;
this.ctUrl = null;
this.logger = logger;
}
abstract boolean init();
abstract boolean offer(K k, APISample apiSample);
abstract boolean canOffer(K k);
public AgentConfig getOperatingConfig() {
return this.config;
}
public abstract boolean offer(ApiBufferKey apiBufferKey, APISample apiSample);
public abstract boolean canOffer(ApiBufferKey apiBufferKey);
public boolean shutdown() {
logger.info("Shutting down ApiSampleBufferManagerWorker");
if (bufferSyncExecutorService.isShutdown()) {
cleanUpBufferMap();
return true;
}
try {
bufferSyncExecutorService.shutdown(); // Disable new tasks from being submitted
if (!bufferSyncExecutorService.awaitTermination(10, TimeUnit.SECONDS)) {
bufferSyncExecutorService.shutdownNow(); // Cancel currently executing tasks
if (!bufferSyncExecutorService.awaitTermination(10, TimeUnit.SECONDS)) {
logger.error("Still not able to shutdown ApiSampleBufferManagerWorker's bufferSyncExecutorService");
}
}
} catch (InterruptedException e) {
logger.error("Error while shutting down ApiSampleBufferManagerWorker's bufferSyncExecutorService", e);
}
cleanUpBufferMap();
return bufferSyncExecutorService.isShutdown();
}
private void cleanUpBufferMap() {
syncForKeys();
for (ApiBufferKey key : this.bufferMap.keySet()) {
Buffer buffer = this.bufferMap.get(key);
if (null != buffer) {
buffer.clear();
}
}
this.bufferMap.clear();
}
abstract void syncForKey(ApiBufferKey key);
private void syncForKeys() {
Set<ApiBufferKey> keys = this.bufferMap.keySet();
if (null == keys || keys.size() == 0) {
return;
}
keys.forEach(this::syncForKey);
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/buffer/Constants.java
|
package ai.apiverse.apisuite.mirror.agent.buffer;
public class Constants {
public static final String CONFIG_URI = "/api/v1/mirror/agent-config";
public static final String SAMPLE_INGESTION_URI = "/api/v1/mirror/data-ingestion/api-sample";
public static final String CODE_SCAN_INGESTION_URI = "/api/v1/mirror/data-ingestion/code-sample";
public static String API_KEY_HEADER = "X-API-KEY";
public static String API_KEY_HEADER_VALUE = "test123";
public static String PARTNER_ID_HEADER = "X-PARTNER-ID";
public static String PARTNER_ID_HEADER_VALUE = "test";
public static String SERVICE_NAME_HEADER = "X-SERVICE-NAME";
public static String TEAM_NAME_HEADER = "X-TEAM-NAME";
public static String ENV_NAME_HEADER = "X-ENV-NAME";
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/buffer/DiscoveredApiBufferManager.java
|
package ai.apiverse.apisuite.mirror.agent.buffer;
import ai.apiverse.apisuite.mirror.agent.ApimonitorHTTPConnection;
import ai.apiverse.apisuite.mirror.agent.SDKLogger;
import ai.apiverse.apisuite.mirror.agent.config.ConfigManager;
import ai.apiverse.apisuite.mirror.models.data.APISample;
import ai.apiverse.apisuite.mirror.models.data.AgentConfig;
import lombok.NonNull;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
public class DiscoveredApiBufferManager extends AbstractBufferManager {
private final ApimonitorHTTPConnection apimonitorHTTPConnection;
private final String ctUrl;
private final SDKLogger logger;
public DiscoveredApiBufferManager(ConfigManager configManager, ApimonitorHTTPConnection apimonitorHTTPConnection, String ctUrl, SDKLogger logger) {
super(configManager, logger);
this.apimonitorHTTPConnection = apimonitorHTTPConnection;
this.ctUrl = ctUrl;
this.logger = logger;
}
BufferManagerWorker<ApiBufferKey> createWorker(AgentConfig newConfig) {
return new DiscoveredApiBufferManagerWorker(newConfig, apimonitorHTTPConnection, logger);
}
public class DiscoveredApiBufferManagerWorker extends BufferManagerWorker<ApiBufferKey> {
private final ApimonitorHTTPConnection apimonitorHTTPConnection;
private final Semaphore semaphore;
public DiscoveredApiBufferManagerWorker(@NonNull AgentConfig config, ApimonitorHTTPConnection apimonitorHTTPConnection, SDKLogger logger) {
super(config, ctUrl, logger);
semaphore = new Semaphore(config.getDiscoveryBufferSize());
this.apimonitorHTTPConnection = apimonitorHTTPConnection;
}
@Override
public boolean init() {
return true;
}
public boolean offer(ApiBufferKey apiBufferKey, APISample apiSample) {
bufferMap.computeIfAbsent(apiBufferKey, (key) -> new SimpleBuffer(getOperatingConfig().getDiscoveryBufferSizePerApi()));
Buffer buffer = bufferMap.get(apiBufferKey);
if (buffer != null) {
return buffer.offer(apiSample);
} else {
logger.error("Buffer found null for " + apiBufferKey.getUri());
}
return false;
}
public boolean canOffer(ApiBufferKey apiBufferKey) {
if (semaphore.tryAcquire()) {
boolean canOffer = false;
if (getOperatingConfig().getCaptureApiSample()) {
Buffer buffer = bufferMap.get(apiBufferKey);
if (null != buffer) {
canOffer = buffer.canOffer();
} else {
canOffer = bufferMap.size() < getOperatingConfig().getDiscoveryBufferSize();
}
}
semaphore.release();
return canOffer;
}
return false;
}
void syncForKey(ApiBufferKey key) {
try {
Buffer buffer = bufferMap.get(key);
if (null == buffer) {
logger.error("Buffer is null for " + key.getUri());
return;
}
int iterations = buffer.getContentCount();
if (iterations == 0) {
bufferMap.remove(key);
return;
}
List<APISample> contents = new ArrayList<>();
while (iterations-- > 0) {
APISample apiSample = buffer.poll();
if (null == apiSample) {
bufferMap.remove(key);
break;
}
contents.add(apiSample);
}
if (contents.size() == 0) {
return;
}
this.apimonitorHTTPConnection.sendSamples(contents);
} catch (Exception exception) {
logger.error("Error inside syncForKey for key " + key.getUri(), exception);
}
}
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/buffer/NoOpBufferManagerWorker.java
|
package ai.apiverse.apisuite.mirror.agent.buffer;
import ai.apiverse.apisuite.mirror.agent.SDKLogger;
import ai.apiverse.apisuite.mirror.models.data.APISample;
import ai.apiverse.apisuite.mirror.models.data.AgentConfig;
public class NoOpBufferManagerWorker<K> extends BufferManagerWorker<K> {
AgentConfig config;
public NoOpBufferManagerWorker(SDKLogger logger) {
super(logger);
config = AgentConfig.noOpAgentConfig;
}
@Override
public boolean init() {
return true;
}
@Override
public AgentConfig getOperatingConfig() {
return config;
}
@Override
public boolean offer(ApiBufferKey apiBufferKey, APISample apiSample) {
return false;
}
@Override
public boolean canOffer(ApiBufferKey apiBufferKey) {
return false;
}
@Override
public boolean offer(K k, APISample apiSample) {
return false;
}
public boolean canOffer(K k) {
return false;
}
@Override
public boolean shutdown() {
return true;
}
@Override
void syncForKey(ApiBufferKey key) {
return;
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/buffer/RegisteredApiBufferManager.java
|
package ai.apiverse.apisuite.mirror.agent.buffer;
import ai.apiverse.apisuite.mirror.agent.ApimonitorHTTPConnection;
import ai.apiverse.apisuite.mirror.agent.SDKLogger;
import ai.apiverse.apisuite.mirror.agent.config.ConfigManager;
import ai.apiverse.apisuite.mirror.models.data.APISample;
import ai.apiverse.apisuite.mirror.models.data.AgentConfig;
import lombok.NonNull;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
public class RegisteredApiBufferManager extends AbstractBufferManager {
private final ApimonitorHTTPConnection apimonitorHTTPConnection;
private final String ctUrl;
private final SDKLogger logger;
public RegisteredApiBufferManager(ConfigManager configManager, ApimonitorHTTPConnection apimonitorHTTPConnection, String ctUrl, SDKLogger logger) {
super(configManager, logger);
this.apimonitorHTTPConnection = apimonitorHTTPConnection;
this.ctUrl = ctUrl;
this.logger = logger;
}
BufferManagerWorker<ApiBufferKey> createWorker(AgentConfig newConfig) {
return new RegisteredApiBufferManagerWorker(newConfig, apimonitorHTTPConnection, logger);
}
public class RegisteredApiBufferManagerWorker extends BufferManagerWorker<ApiBufferKey> {
private final ApimonitorHTTPConnection apimonitorHTTPConnection;
private final Semaphore semaphore;
public RegisteredApiBufferManagerWorker(@NonNull AgentConfig config, ApimonitorHTTPConnection apimonitorHTTPConnection, SDKLogger logger) {
super(config, ctUrl, logger);
this.apimonitorHTTPConnection = apimonitorHTTPConnection;
semaphore = new Semaphore(getRegisteredApiCountToCapture());
}
@Override
public boolean init() {
return true;
}
public boolean offer(ApiBufferKey apiBufferKey, APISample apiSample) {
bufferMap.computeIfAbsent(apiBufferKey, (key) -> new SimpleBuffer(getRegisteredApiBufferSize(apiBufferKey)));
Buffer buffer = bufferMap.get(apiBufferKey);
if (buffer != null) {
return buffer.offer(apiSample);
} else {
logger.error("Buffer found null for " + apiBufferKey.getUri());
}
return false;
}
public boolean canOffer(ApiBufferKey apiBufferKey) {
if (!getOperatingConfig().getCaptureApiSample()) {
return false;
}
int bufferSize = getRegisteredApiBufferSize(apiBufferKey);
if (bufferSize == 0) {
return false;
}
Buffer buffer = bufferMap.get(apiBufferKey);
if (semaphore.tryAcquire()) {
boolean canOffer = false;
if (null == buffer) {
canOffer = true;
} else {
canOffer = buffer.canOffer();
}
semaphore.release();
return canOffer;
}
return false;
}
public int getRegisteredApiBufferSize(ApiBufferKey apiBufferKey) {
AgentConfig agentConfig = getOperatingConfig();
if (null == agentConfig.getRegisteredApiConfigs() || agentConfig.getRegisteredApiConfigs().size() == 0) {
return 0;
}
for (AgentConfig.ApiConfig apiConfig : agentConfig.getRegisteredApiConfigs()) {
if (apiConfig.getMethod() == apiBufferKey.getMethod() && apiConfig.getUri().equals(apiBufferKey.getUri())) {
return apiConfig.getBufferSize();
}
}
return 0;
}
public int getRegisteredApiCountToCapture() {
AgentConfig agentConfig = getOperatingConfig();
if (null == agentConfig.getRegisteredApiConfigs() || agentConfig.getRegisteredApiConfigs().size() == 0) {
return 0;
}
int totalApis = 0;
for (AgentConfig.ApiConfig apiConfig : agentConfig.getRegisteredApiConfigs()) {
if (null != apiConfig.getBufferSize()) {
totalApis += apiConfig.getBufferSize();
}
}
return totalApis;
}
void syncForKey(ApiBufferKey key) {
try {
Buffer buffer = bufferMap.get(key);
if (null == buffer) {
logger.error("Buffer is null for " + key.getUri());
return;
}
int iterations = buffer.getContentCount();
while (iterations-- > 0) {
APISample apiSample = buffer.poll();
if (null == apiSample) {
break;
}
List<APISample> dataList = new ArrayList<>();
dataList.add(apiSample);
this.apimonitorHTTPConnection.sendSamples(dataList);
}
} catch (Exception exception) {
logger.error("Error inside syncForKey for key " + key.getUri(), exception);
}
}
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/buffer/SimpleBuffer.java
|
package ai.apiverse.apisuite.mirror.agent.buffer;
import ai.apiverse.apisuite.mirror.models.data.APISample;
import java.util.concurrent.ArrayBlockingQueue;
// Thread-safe
public class SimpleBuffer implements Buffer {
private final ArrayBlockingQueue<APISample> arrayBlockingQueue;
int size;
public SimpleBuffer(int size) {
this.size = size;
this.arrayBlockingQueue = new ArrayBlockingQueue<APISample>(size);
}
@Override
public boolean offer(APISample apiSample) {
return this.arrayBlockingQueue.offer(apiSample);
}
@Override
public boolean canOffer() {
return this.size > 0 && this.arrayBlockingQueue.remainingCapacity() > 0;
}
@Override
public APISample poll() {
return this.arrayBlockingQueue.poll();
}
@Override
public boolean clear() {
this.arrayBlockingQueue.clear();
return true;
}
public int getContentCount() {
return arrayBlockingQueue.size();
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/commons/ObservedApi.java
|
package ai.apiverse.apisuite.mirror.agent.commons;
import ai.apiverse.apisuite.mirror.models.constant.HttpRequestMethod;
import ai.apiverse.apisuite.mirror.models.data.AgentConfig;
import ai.apiverse.apisuite.mirror.models.data.URI;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.experimental.FieldDefaults;
@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
@RequiredArgsConstructor
@Getter
@Setter
public class ObservedApi {
URI uri;
HttpRequestMethod method;
public ObservedApi(String uriPath, HttpRequestMethod method) {
this.uri = URI.getNonTemplatedURI(uriPath);
this.method = method;
}
public boolean matches(AgentConfig.ApiConfig apiConfig) {
if (apiConfig == null) {
return false;
}
if (this.method != apiConfig.getMethod()) {
return false;
}
return this.uri.equals(apiConfig.getUri());
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/commons/SimpleSuccessResponse.java
|
package ai.apiverse.apisuite.mirror.agent.commons;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class SimpleSuccessResponse {
private boolean status = true;
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/config/AgentConfigUtils.java
|
package ai.apiverse.apisuite.mirror.agent.config;
import ai.apiverse.apisuite.mirror.models.data.AgentConfig;
import ai.apiverse.apisuite.mirror.models.data.URI;
public class AgentConfigUtils {
public static boolean isConfigValid(AgentConfig agentConfig) {
if (null == agentConfig) {
return false;
}
if (null == agentConfig.getBufferSyncFreqInSec()) {
return false;
}
if (null == agentConfig.getConfigFetchFreqInSec()) {
return false;
}
if (null == agentConfig.getCaptureApiSample()) {
return false;
}
if (null == agentConfig.getDiscoveryBufferSize()) {
return false;
}
if (null == agentConfig.getDiscoveryBufferSizePerApi()) {
return false;
}
if (null != agentConfig.getRegisteredApiConfigs()) {
for (AgentConfig.ApiConfig apiConfig : agentConfig.getRegisteredApiConfigs()) {
if (!isApiConfigValid(apiConfig)) {
return false;
}
}
}
return true;
}
static boolean isApiConfigValid(AgentConfig.ApiConfig apiConfig) {
if (null == apiConfig) {
return false;
}
if (!isURIValid(apiConfig.getUri())) {
return false;
}
if (null == apiConfig.getMethod()) {
return false;
}
if (null == apiConfig.getBufferSize()) {
return false;
}
if (null == apiConfig.getCaptureSampleRequest()) {
return false;
}
if (null == apiConfig.getCaptureSampleResponse()) {
return false;
}
return true;
}
static boolean isURIValid(URI uri) {
if (null == uri) {
return false;
}
if (null == uri.getUriPath() || uri.getUriPath().length() == 0) {
return false;
}
return true;
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/config/ConfigManager.java
|
package ai.apiverse.apisuite.mirror.agent.config;
public interface ConfigManager {
boolean init();
boolean subscribeToUpdates(ConfigUpdateListener configUpdateListener);
boolean shutdown();
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/config/ConfigUpdateListener.java
|
package ai.apiverse.apisuite.mirror.agent.config;
import ai.apiverse.apisuite.mirror.models.data.AgentConfig;
public interface ConfigUpdateListener {
void onSuccessfulConfigUpdate(AgentConfig agentConfig);
void onErroneousConfigUpdate();
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/agent/config/SimpleConfigManager.java
|
package ai.apiverse.apisuite.mirror.agent.config;
import ai.apiverse.apisuite.mirror.agent.ApimonitorHTTPConnection;
import ai.apiverse.apisuite.mirror.agent.SDKLogger;
import ai.apiverse.apisuite.mirror.agent.SDKVersion;
import ai.apiverse.apisuite.mirror.models.data.AgentConfig;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public final class SimpleConfigManager implements ConfigManager {
private final String ctUrl;
private final ApimonitorHTTPConnection apimonitorHTTPConnection;
private final String userApplicationName;
private final List<ConfigUpdateListener> configUpdateListeners = Collections.synchronizedList(new LinkedList<>());
private final Map<String, String> configHeader;
private final String agentId;
private ScheduledExecutorService executorService;
private SDKLogger logger;
public SimpleConfigManager(final String ctUrl,
final String userApplicationName,
final String agentId,
ApimonitorHTTPConnection apimonitorHTTPConnection,
SDKLogger logger) {
this.ctUrl = ctUrl;
this.userApplicationName = userApplicationName;
this.agentId = agentId;
this.apimonitorHTTPConnection = apimonitorHTTPConnection;
this.logger = logger;
configHeader = new HashMap<>();
configHeader.put(SDKVersion.MAJOR_VERSION_KEY, SDKVersion.MAJOR_VERSION);
configHeader.put(SDKVersion.MINOR_VERSION_KEY, SDKVersion.MINOR_VERSION);
}
public boolean subscribeToUpdates(ConfigUpdateListener configUpdateListener) {
configUpdateListeners.add(configUpdateListener);
return true;
}
public synchronized boolean shutdown() {
logger.info("Shutting down SimpleConfigManager");
if (null == executorService) {
logger.info("Shutting down executorService");
return true;
}
if (executorService.isShutdown()) {
return true;
}
try {
executorService.shutdown(); // Disable new tasks from being submitted
if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) {
executorService.shutdownNow(); // Cancel currently executing tasks
if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) {
logger.error("Still not able to shutdown SimpleConfigManager's executorService");
}
}
} catch (InterruptedException e) {
logger.error("Error while shutting down SimpleConfigManager's executorService", e);
}
return executorService.isShutdown();
}
public synchronized boolean init() {
try {
executorService = Executors.newSingleThreadScheduledExecutor(new CustomizableThreadFactory("config-"));
scheduleConfigRefresh(60);
} catch (Exception e) {
logger.error("Error in SimpleConfigManager's init()", e);
return false;
}
return true;
}
private void scheduleConfigRefresh(int timeInSecs) {
Runnable runnable = () -> {
try {
ConfigOrError configOrError = fetchConfig();
if (null != configOrError.errorCode) {
scheduleConfigRefresh(60);
onUnSuccessfulConfigFetch(configOrError.errorCode);
} else {
scheduleConfigRefresh(configOrError.getAgentConfig().getConfigFetchFreqInSec());
onSuccessfulConfigFetch(configOrError.agentConfig);
}
} catch (Exception e) {
logger.error("Error in SimpleConfigManager's scheduleConfigRefresh()", e);
}
};
executorService.schedule(runnable, timeInSecs, TimeUnit.SECONDS);
}
private ConfigOrError fetchConfig() {
try {
Map<String, String> queryParams = new HashMap<>();
queryParams.put("appName", userApplicationName);
queryParams.put("agentId", agentId);
AgentConfig agentConfig = this.apimonitorHTTPConnection.getSDKConfig();
if (null == agentConfig) {
logger.error("Received null config :");
return new ConfigOrError(null, ConfigOrError.ErrorCode.INVALID_CONFIG);
}
if (AgentConfigUtils.isConfigValid(agentConfig)) {
return new ConfigOrError(agentConfig, null);
} else {
logger.error("Received invalid config :" + agentConfig);
return new ConfigOrError(null, ConfigOrError.ErrorCode.INVALID_CONFIG);
}
} catch (Exception exception) {
logger.error("Error while fetching config", exception);
return new ConfigOrError(null, ConfigOrError.ErrorCode.PARSE_ERROR);
}
}
private void onSuccessfulConfigFetch(AgentConfig agentConfig) {
for (ConfigUpdateListener configUpdateListener : configUpdateListeners) {
configUpdateListener.onSuccessfulConfigUpdate(agentConfig);
}
}
private void onUnSuccessfulConfigFetch(ConfigOrError.ErrorCode errorCode) {
for (ConfigUpdateListener configUpdateListener : configUpdateListeners) {
configUpdateListener.onErroneousConfigUpdate();
}
}
@RequiredArgsConstructor
@Getter
@Setter
private static class ConfigOrError {
private final AgentConfig agentConfig;
private final ErrorCode errorCode;
private enum ErrorCode {
TIMEOUT,
PARSE_ERROR,
INVALID_CONFIG
}
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/models
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/models/constant/ApimonitorCommonConstant.java
|
package ai.apiverse.apisuite.mirror.models.constant;
import lombok.Getter;
public interface ApimonitorCommonConstant {
String DATA_CATEGORY_MESSAGE_ATTRIBUTE_KEY = "DATA_CATEGORY";
String CONTENT_TYPE_HEADER_LOWER_CASE = "content-type";
String CONTENT_TYPE_HEADER_JSON_VALUE = "application/json";
String MASKING_RULES_CONFIGURATION_NAME = "PIIMaskingRules";
String DEFAULT_MASK_REPLACEMENT = "MASKED";
String MASKED_VALUE_SUFFIX = "SL_MASK";
enum DataSizeUnit {
KB,
MB,
GB
}
enum DataCategory {
SAMPLE_DATA
}
enum ContentType {
JSON("application/json"),
FORM_URLENCODED("application/x-www-form-urlencoded"),
TEXT("text/plain"),
MULTIPART_FORM_DATA("multipart/form-data"),
UNKNOWN("unknown_header");
@Getter
String headerValue;
ContentType(String headerValue) {
this.headerValue = headerValue;
}
public static ContentType getContentTypeFrom(String headerValue) {
if (null == headerValue) {
return ContentType.UNKNOWN;
}
for (ContentType contentType : ContentType.values()) {
if (headerValue.toLowerCase().contains(contentType.headerValue.toLowerCase())) {
return contentType;
}
}
return ContentType.UNKNOWN;
}
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/models
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/models/constant/HttpRequestMethod.java
|
package ai.apiverse.apisuite.mirror.models.constant;
public enum HttpRequestMethod {
GET,
HEAD,
POST,
PUT,
PATCH,
DELETE,
OPTIONS,
TRACE;
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/models
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/models/data/APISample.java
|
package ai.apiverse.apisuite.mirror.models.data;
import ai.apiverse.apisuite.mirror.models.constant.HttpRequestMethod;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
import lombok.experimental.FieldDefaults;
import java.util.Map;
@Getter
@Setter
@NoArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
@JsonIgnoreProperties(ignoreUnknown = true)
@ToString
public class APISample {
String rawUri;
String applicationName;
String hostName;
int port;
String scheme;
HttpRequestMethod method;
Map<String, String[]> parameters;
Map<String, String> requestHeaders;
Map<String, String> responseHeaders;
int statusCode;
String requestPayload;
String responsePayload;
String uncaughtExceptionMessage;
Boolean payloadCaptureAttempted;
Boolean requestPayloadCaptureAttempted;
Boolean responsePayloadCaptureAttempted;
Long latency;
URI uri;
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/models
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/models/data/AgentConfig.java
|
package ai.apiverse.apisuite.mirror.models.data;
import ai.apiverse.apisuite.mirror.models.constant.HttpRequestMethod;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
import lombok.experimental.FieldDefaults;
import java.util.*;
// This class is Immutable.
@Builder
@Getter
@Setter
@FieldDefaults(level = AccessLevel.PRIVATE)
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public final class AgentConfig {
public static final AgentConfig noOpAgentConfig;
static {
noOpAgentConfig = new AgentConfig();
noOpAgentConfig.setBufferSyncFreqInSec(20);
noOpAgentConfig.setCaptureApiSample(false);// changed to true for testing purpose
// noOpAgentConfig.setCaptureApiSample(true);
noOpAgentConfig.setConfigFetchFreqInSec(120);
noOpAgentConfig.setDiscoveryBufferSize(0);
noOpAgentConfig.setDiscoveryBufferSizePerApi(0);
noOpAgentConfig.setRegisteredApiConfigs(new ArrayList<>());
noOpAgentConfig.setTimestamp(new Date(0));
}
Integer bufferSyncFreqInSec;
Boolean captureApiSample;
Integer configFetchFreqInSec;
List<ApiConfig> registeredApiConfigs = new ArrayList<>();
Date timestamp;
Integer discoveryBufferSize;
Integer discoveryBufferSizePerApi;
List<BlackListRule> blackListRules = new ArrayList<>();
Map<String, String> maskHeaders = new HashMap<>();
@EqualsAndHashCode
@Getter
@Setter
@FieldDefaults(level = AccessLevel.PRIVATE)
@NoArgsConstructor
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public static class ApiConfig {
URI uri;
HttpRequestMethod method;
Integer bufferSize;
Boolean captureSampleRequest;
Boolean captureSampleResponse;
public ApiConfig(URI uri, HttpRequestMethod method, int bufferSize, boolean captureSampleRequest, boolean captureSampleResponse) {
this.uri = uri;
this.method = method;
this.bufferSize = bufferSize;
this.captureSampleRequest = captureSampleRequest;
this.captureSampleResponse = captureSampleResponse;
}
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/models
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/models/data/ApiOwner.java
|
package ai.apiverse.apisuite.mirror.models.data;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AccessLevel;
import lombok.Data;
import lombok.experimental.FieldDefaults;
@JsonIgnoreProperties(ignoreUnknown = true)
@Data
@FieldDefaults(level = AccessLevel.PRIVATE)
public class ApiOwner {
String env;
String team;
String serviceName;
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/models
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/models/data/ApiSampleWrapper.java
|
package ai.apiverse.apisuite.mirror.models.data;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AccessLevel;
import lombok.Data;
import lombok.experimental.FieldDefaults;
import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true)
@Data
@FieldDefaults(level = AccessLevel.PRIVATE)
public class ApiSampleWrapper {
ApiOwner apiOwner;
List<APISample> apiSamples;
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/models
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/models/data/BlackListRule.java
|
package ai.apiverse.apisuite.mirror.models.data;
import ai.apiverse.apisuite.mirror.models.constant.HttpRequestMethod;
import ai.apiverse.apisuite.mirror.utils.ApimonitorCommonUtils;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.List;
@Getter
@Setter
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class BlackListRule {
// blackListType: endsWith or absolute. the reason it is not a enum is so that
// sdk does not break in case there is a version mismatch between sdk and
// commons
String blackListType;
List<String> matchValues;
HttpRequestMethod method;
public boolean isValid() {
if (ApimonitorCommonUtils.isBlank(blackListType)) {
return false;
}
if (matchValues == null) {
return false;
}
return true;
}
public boolean matchesUri(URI uri, HttpRequestMethod httpMethod) {
if (!isValid()) {
return false;
}
if (null == httpMethod || null == uri) {
return false;
}
if (null != this.method && !this.method.equals(httpMethod)) {
return false;
}
if (this.blackListType.equalsIgnoreCase("endsWith")) {
for (String matchValue : this.matchValues) {
if (uri.getUriPath().toLowerCase().endsWith(matchValue.toLowerCase())) {
return true;
}
}
} else if (blackListType.equalsIgnoreCase("absolute")) {
for (String matchValue : matchValues) {
if (uri.equals(URI.getURI(matchValue))) {
return true;
}
}
}
return false;
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/models
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/models/data/URI.java
|
package ai.apiverse.apisuite.mirror.models.data;
import ai.apiverse.apisuite.mirror.utils.URIUtils;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
import lombok.experimental.FieldDefaults;
import java.util.List;
import java.util.stream.Collectors;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
@JsonIgnoreProperties(ignoreUnknown = true)
@ToString
public class URI {
String uriPath;
boolean hasPathVariable;
public static URI getNonTemplatedURI(String uriPath) {
return new URI(uriPath, false);
}
public static URI getURI(String uriPath) {
List<String> pathSegments = URIUtils.getPathSegments(uriPath);
boolean isTemplateURI = false;
for (String pathSegment : pathSegments) {
if (URIUtils.isPathSegmentTemplate(pathSegment)) {
isTemplateURI = true;
break;
}
}
return new URI(uriPath, isTemplateURI);
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null) {
return false;
}
// type check and cast
if (getClass() != object.getClass()) {
return false;
}
URI otherURI = (URI) object;
if (!isHasPathVariable() && !otherURI.isHasPathVariable()) {
if (getUriPath().equals(otherURI.getUriPath())) {
return true;
}
}
List<String> pathSegments = URIUtils.getPathSegments(uriPath);
List<String> otherURIPathSegments = URIUtils.getPathSegments(otherURI.getUriPath());
if (pathSegments.size() != otherURIPathSegments.size()) {
return false;
}
for (int idx = 0; idx < pathSegments.size(); idx++) {
if (!URIUtils.arePathSegmentMatching(pathSegments.get(idx), otherURIPathSegments.get(idx))) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
final int PRIME = 59;
int result = 1;
result = result * PRIME + URIUtils.getPathSegments(uriPath).size();
return result;
}
public int getSize() {
return URIUtils.getPathSegments(this.uriPath).size();
}
@JsonIgnore
public List<PathSegment> getPathSegments() {
return URIUtils.getPathSegments(this.uriPath).stream().map(URIUtils::getPathSegment).collect(Collectors.toList());
}
public enum SegmentTemplateDataType {
NUMBER("{number}"),
STRING("{string}"),
UUID("{uuid}"),
UNKNOWN("{unknown}");
@Getter
String pathDisplayName;
SegmentTemplateDataType(String pathDisplayName) {
this.pathDisplayName = pathDisplayName;
}
public static SegmentTemplateDataType getTemplateDataTypeByDisplayName(String pathDisplayName) {
for (SegmentTemplateDataType dataType : SegmentTemplateDataType.values()) {
if (dataType.pathDisplayName.equals(pathDisplayName)) {
return dataType;
}
}
return SegmentTemplateDataType.UNKNOWN;
}
}
@Getter
@Setter
@NoArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
@JsonIgnoreProperties(ignoreUnknown = true)
public static class URIPathVariable {
String variableId;
String variableName;
}
@Getter
@Setter
@NoArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
@JsonIgnoreProperties(ignoreUnknown = true)
public static class PathSegment {
private static final String UNKNOWN_DATA_TYPE_SEGMENT_NAME = "{unknown}";
private static final String INT_DATA_TYPE_SEGMENT_NAME = "{int}";
private static final String STRING_DATA_TYPE_SEGMENT_NAME = "{string}";
private static final String UUID_DATA_TYPE_SEGMENT_NAME = "{uuid}";
String segmentName;
boolean templatedSegment;
SegmentTemplateDataType segmentTemplateDataType;
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null) {
return false;
}
// type check and cast
if (getClass() != object.getClass()) {
return false;
}
PathSegment otherSegment = (PathSegment) object;
if (this.isTemplatedSegment() && otherSegment.isTemplatedSegment()) {
return this.segmentTemplateDataType == otherSegment.segmentTemplateDataType;
}
if (this.isTemplatedSegment() || otherSegment.isTemplatedSegment()) {
return false;
}
return this.segmentName.equals(otherSegment.getSegmentName());
}
@Override
public int hashCode() {
return 79;
}
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/utils/ApimonitorCommonUtils.java
|
package ai.apiverse.apisuite.mirror.utils;
import java.util.ArrayList;
import java.util.List;
public class ApimonitorCommonUtils {
public static boolean isBlank(CharSequence cs) {
int strLen = length(cs);
if (strLen == 0) {
return true;
} else {
for (int i = 0; i < strLen; ++i) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
}
public static List<String> split(String str, String delimiter) {
if (null == str || str.length() == 0) {
return new ArrayList<>();
}
String[] splits = str.split(delimiter);
List<String> stringList = new ArrayList<>();
for (String split : splits) {
if (null == split || split.length() == 0) {
continue;
}
stringList.add(split);
}
return stringList;
}
public static int length(CharSequence cs) {
return cs == null ? 0 : cs.length();
}
public static boolean isEmpty(CharSequence cs) {
return length(cs) == 0;
}
public static boolean isParsableNumber(String str) {
if (isEmpty(str)) {
return false;
} else if (str.charAt(str.length() - 1) == '.') {
return false;
} else if (str.charAt(0) == '-') {
return str.length() == 1 ? false : withDecimalsParsing(str, 1);
} else {
return withDecimalsParsing(str, 0);
}
}
private static boolean withDecimalsParsing(String str, int beginIdx) {
int decimalPoints = 0;
for (int i = beginIdx; i < str.length(); ++i) {
boolean isDecimalPoint = str.charAt(i) == '.';
if (isDecimalPoint) {
++decimalPoints;
}
if (decimalPoints > 1) {
return false;
}
if (!isDecimalPoint && !Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/mirror/utils/URIUtils.java
|
package ai.apiverse.apisuite.mirror.utils;
import ai.apiverse.apisuite.mirror.models.data.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class URIUtils {
public static Pattern alphaNumericPattern = Pattern.compile("^[a-zA-Z0-9]*$");
/*public static boolean compare(RegisteredApi templatedUri1, RegisteredApi templatedUri2) {
List<String> templatedPathSegments1 = getPathSegments(templatedUri1.getTemplatedUri());
List<String> templatedPathSegments2 = getPathSegments(templatedUri2.getTemplatedUri());
if (templatedPathSegments1.size() == templatedPathSegments2.size()) {
for (int i = 0; i < templatedPathSegments1.size(); i++) {
if (isPathSegmentTemplate(templatedPathSegments1.get(i)) || isPathSegmentTemplate(templatedPathSegments2.get(i))) {
continue; // If the segment is templated, we skip it's comparison.
} else {
if (!templatedPathSegments1.get(i).equals(templatedPathSegments2.get(i))) {
return false; // If one of the segment doesn't matches, we return false.
}
}
}
// If after the loop, we still haven't returned, it means all the segments had a match.
return true;
} else {
return false;
}
}*/
public static boolean arePathSegmentMatching(String pathVariableA, String pathVariableB) {
if (null == pathVariableA && null == pathVariableB) {
return true;
}
if (null == pathVariableA || null == pathVariableB) {
return false;
}
if (ApimonitorCommonUtils.isBlank(pathVariableA) && ApimonitorCommonUtils.isBlank(pathVariableB)) {
return true;
}
if (ApimonitorCommonUtils.isBlank(pathVariableA) || ApimonitorCommonUtils.isBlank(pathVariableB)) {
return false;
}
if (pathVariableA.equals(pathVariableB)) {
return true;
}
boolean isPathVariableATemplate = isPathSegmentTemplate(pathVariableA);
boolean isPathVariableBTemplate = isPathSegmentTemplate(pathVariableB);
if (isPathVariableATemplate && isPathVariableBTemplate) {
return false;
}
if (!isPathVariableATemplate && !isPathVariableBTemplate) {
return false;
}
if (isPathVariableATemplate) {
return pathSegmentBelongsTo(pathVariableB, pathVariableA);
} else {
return pathSegmentBelongsTo(pathVariableA, pathVariableB);
}
}
private static boolean pathSegmentBelongsTo(String pathSegment, String pathVariable) {
URI.PathSegment templatePathSegment = getPathSegment(pathVariable);
if (isNumericSegment(templatePathSegment)) {
return isNumeric(pathSegment);
}
if (isUUIDSegment(templatePathSegment)) {
return isUUID(pathSegment) || isIdType(pathSegment);
}
if (templatePathSegment.getSegmentTemplateDataType() == URI.SegmentTemplateDataType.STRING) {
if (isNumeric(pathSegment) || isUUID(pathSegment) || isIdType(pathSegment)) {
return false;
}
}
return true;
}
// Utility functions.
public static boolean isPathSegmentTemplate(String pathSegment) {
if (ApimonitorCommonUtils.isBlank(pathSegment)) {
return false;
}
String trimmedPathSegment = pathSegment.trim();
return trimmedPathSegment.startsWith("{") && trimmedPathSegment.endsWith("}");
}
public static String getVariableId(String pathSegment) {
String trimmedPathSegment = pathSegment.trim();
return trimmedPathSegment.substring(1, trimmedPathSegment.length() - 1);
}
public static List<String> getPathSegments(String uri) {
if (ApimonitorCommonUtils.isBlank(uri)) {
return new ArrayList<>();
}
return ApimonitorCommonUtils.split(uri, "/");
}
public static URI.PathSegment getClosedMatchingPathSegment(URI.PathSegment pathSegment, List<URI.PathSegment> candidates) {
if (null == pathSegment || null == candidates || candidates.size() == 0) {
return null;
}
if (pathSegment.isTemplatedSegment()) {
return candidates.
stream().
filter(URI.PathSegment::isTemplatedSegment).
filter(candidate -> pathSegment.getSegmentTemplateDataType() == candidate.getSegmentTemplateDataType()).
findFirst().orElse(null);
} else {
URI.PathSegment exactMatch = candidates.
stream().
filter(candidate -> !candidate.isTemplatedSegment()).
filter(candidate -> candidate.getSegmentName().equals(pathSegment.getSegmentName())).
findFirst().orElse(null);
if (null != exactMatch) {
return exactMatch;
}
if (isNumericSegment(pathSegment)) {
return closedMatchingTemplate(candidates, URI.SegmentTemplateDataType.NUMBER).orElse(null);
}
if (isUUIDSegment(pathSegment)) {
return closedMatchingTemplate(candidates, URI.SegmentTemplateDataType.UUID).orElse(null);
}
return closedMatchingTemplate(candidates, URI.SegmentTemplateDataType.STRING).orElse(null);
}
}
public static Optional<URI.PathSegment> closedMatchingTemplate(List<URI.PathSegment> candidates, URI.SegmentTemplateDataType type) {
return candidates.
stream().
filter(URI.PathSegment::isTemplatedSegment).
filter(candidate -> candidate.getSegmentTemplateDataType() == type).
findFirst();
}
public static boolean isNumericSegment(URI.PathSegment pathSegment) {
if (pathSegment.isTemplatedSegment()) {
return pathSegment.getSegmentTemplateDataType() == URI.SegmentTemplateDataType.NUMBER;
} else {
return ApimonitorCommonUtils.isParsableNumber(pathSegment.getSegmentName());
}
}
public static boolean isUUIDSegment(URI.PathSegment pathSegment) {
if (pathSegment.isTemplatedSegment()) {
return pathSegment.getSegmentTemplateDataType() == URI.SegmentTemplateDataType.UUID;
} else {
return isUUID(pathSegment.getSegmentName()) || isIdType(pathSegment.getSegmentName());
}
}
public static boolean isIdType(String pathString) {
if (null == pathString || pathString.length() < 10) {
return false;
}
int intCount = 0;
int charCount = 0;
for (int i = 0; i < pathString.length(); i++) {
if (Character.isDigit(pathString.charAt(i))) {
intCount += 1;
} else if (Character.isLetter(pathString.charAt(i))) {
charCount += 1;
}
}
if (charCount > 1 && intCount > 4) {
return true;
}
return false;
}
public static boolean isUUID(String string) {
List<String> splits = ApimonitorCommonUtils.split(string, "-");
if (splits.size() != 5) {
return false;
}
for (String split : splits) {
Matcher matcher = alphaNumericPattern.matcher(split);
if (!matcher.matches()) {
return false;
}
}
return true;
}
public static boolean isNumeric(String string) {
return ApimonitorCommonUtils.isParsableNumber(string);
}
public static List<URI.PathSegment> filterNumericNonTemplateSegments(List<URI.PathSegment> segments) {
if (null == segments) {
return null;
}
return segments.
stream().
filter(URIUtils::isNumericNonTemplateSegment).
collect(Collectors.toList());
}
public static boolean isNumericNonTemplateSegment(URI.PathSegment pathSegment) {
if (null == pathSegment) {
return false;
}
if (pathSegment.isTemplatedSegment()) {
return false;
}
return isNumeric(pathSegment.getSegmentName());
}
public static List<URI.PathSegment> filterUUIDNonTemplateSegments(List<URI.PathSegment> segments) {
if (null == segments) {
return null;
}
return segments.
stream().
filter(URIUtils::isUUIDNonTemplateSegment).
collect(Collectors.toList());
}
public static boolean isUUIDNonTemplateSegment(URI.PathSegment pathSegment) {
if (null == pathSegment) {
return false;
}
if (pathSegment.isTemplatedSegment()) {
return false;
}
return isUUID(pathSegment.getSegmentName());
}
public static boolean isTemplateSegment(URI.PathSegment pathSegment) {
if (null == pathSegment) {
return false;
}
return pathSegment.isTemplatedSegment();
}
public static URI.PathSegment getDeepClone(URI.PathSegment pathSegment) {
URI.PathSegment cloneSegment = new URI.PathSegment();
cloneSegment.setSegmentTemplateDataType(pathSegment.getSegmentTemplateDataType());
cloneSegment.setTemplatedSegment(pathSegment.isTemplatedSegment());
cloneSegment.setSegmentName(pathSegment.getSegmentName());
return cloneSegment;
}
public static URI.PathSegment getPathSegment(String segmentName) {
if (URIUtils.isPathSegmentTemplate(segmentName)) {
return getTemplateSegment(URI.SegmentTemplateDataType.getTemplateDataTypeByDisplayName(segmentName));
} else {
return getNonTemplateSegment(segmentName);
}
}
public static URI.PathSegment getNonTemplateSegment(String segmentName) {
URI.PathSegment pathSegment = new URI.PathSegment();
pathSegment.setSegmentName(segmentName);
pathSegment.setTemplatedSegment(false);
return pathSegment;
}
public static URI.PathSegment getTemplateSegment(URI.SegmentTemplateDataType segmentTemplateDataType) {
URI.PathSegment pathSegment = new URI.PathSegment();
pathSegment.setTemplatedSegment(true);
pathSegment.setSegmentTemplateDataType(segmentTemplateDataType);
pathSegment.setSegmentName(segmentTemplateDataType.getPathDisplayName());
return pathSegment;
}
public static URI getURIFrom(List<URI.PathSegment> pathSegments) {
if (null == pathSegments || pathSegments.size() == 0) {
return null;
}
StringBuffer stringBuffer = new StringBuffer();
boolean hasPathVariable = false;
for (URI.PathSegment pathSegment : pathSegments) {
stringBuffer.append("/");
hasPathVariable = hasPathVariable || pathSegment.isTemplatedSegment();
stringBuffer.append(pathSegment.getSegmentName());
}
return new URI(stringBuffer.toString(), hasPathVariable);
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/scanner/ApiScannerConfig.java
|
package ai.apiverse.apisuite.scanner;
import ai.apiverse.apisuite.mirror.agent.buffer.Constants;
import ai.apiverse.apisuite.mirror.models.constant.HttpRequestMethod;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializer;
import lombok.Data;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Data
public class ApiScannerConfig {
private static ApiScannerConfig instance;
EndpointService endpointService;
Gson gson = getGsonObject();
private Map<String, String> accessHeaders;
private String userApplicationName;
private Boolean logEnable;
private String apiFlowBackendUrl;
public ApiScannerConfig() {
}
public static ApiScannerConfig getInstance() {
if (instance == null) {
synchronized (ApiScannerConfig.class) {
if (instance == null) {
instance = new ApiScannerConfig();
}
}
}
return instance;
}
private Gson getGsonObject() {
Gson gson = new GsonBuilder()
.registerTypeAdapter(LocalDate.class, (JsonSerializer<LocalDate>) (src, typeOfSrc, context) -> new JsonPrimitive(src.format(DateTimeFormatter.ISO_LOCAL_DATE)))
.registerTypeAdapter(LocalTime.class, (JsonSerializer<LocalTime>) (src, typeOfSrc, context) -> new JsonPrimitive(src.format(DateTimeFormatter.ISO_LOCAL_TIME)))
.registerTypeAdapter(LocalDateTime.class, (JsonSerializer<LocalDateTime>) (src, typeOfSrc, context) -> new JsonPrimitive(src.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)))
.registerTypeAdapter(Instant.class, (JsonSerializer<Instant>) (src, typeOfSrc, context) -> new JsonPrimitive(src.toString()))
.registerTypeAdapter(ZonedDateTime.class, (JsonSerializer<ZonedDateTime>) (src, typeOfSrc, context) -> new JsonPrimitive(src.format(DateTimeFormatter.ISO_ZONED_DATE_TIME)))
.registerTypeAdapter(OffsetDateTime.class, (JsonSerializer<OffsetDateTime>) (src, typeOfSrc, context) -> new JsonPrimitive(src.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)))
.registerTypeAdapter(OffsetTime.class, (JsonSerializer<OffsetTime>) (src, typeOfSrc, context) -> new JsonPrimitive(src.format(DateTimeFormatter.ISO_OFFSET_TIME)))
.registerTypeAdapter(Year.class, (JsonSerializer<Year>) (src, typeOfSrc, context) -> new JsonPrimitive(src.toString()))
.registerTypeAdapter(YearMonth.class, (JsonSerializer<YearMonth>) (src, typeOfSrc, context) -> new JsonPrimitive(src.format(DateTimeFormatter.ofPattern("yyyy-MM"))))
.registerTypeAdapter(MonthDay.class, (JsonSerializer<MonthDay>) (src, typeOfSrc, context) -> new JsonPrimitive(src.format(DateTimeFormatter.ofPattern("MM-dd"))))
.registerTypeAdapter(Duration.class, (JsonSerializer<Duration>) (src, typeOfSrc, context) -> new JsonPrimitive(src.toString()))
.registerTypeAdapter(Period.class, (JsonSerializer<Period>) (src, typeOfSrc, context) -> new JsonPrimitive(src.toString()))
.serializeNulls()
.create();
return gson;
}
EndpointInfo getMappingInfo(RequestMappingInfo info, HandlerMethod method) {
EndpointInfo endpointInfo = new EndpointInfo();
try {
// Extract the URL pattern (assuming only one)
endpointInfo.setPattern(info.getPathPatternsCondition().getPatterns().iterator().next().getPatternString());
// Extract the HTTP method (assuming only one)
Set<RequestMethod> methods = info.getMethodsCondition().getMethods();
if (methods != null && !methods.isEmpty()) {
endpointInfo.setMethod(methods.iterator().next().name());
}
// Extract details about the method
endpointInfo.setMethodDetails(method.getMethod().toString());
// Extract return type
endpointInfo.setReturnParameter(method.getReturnType().getParameterType().getName());
// Extract input parameters
Map<Object, Object> inputParameters = new HashMap<>();
for (MethodParameter parameter : method.getMethodParameters()) {
String type = getParameterType(parameter);
Parameter nativeParameter = parameter.getExecutable().getParameters()[parameter.getParameterIndex()];
String name = nativeParameter.getName();
String paramDto = nativeParameter.getType().getSimpleName().toString();
String qualifiedName = nativeParameter.getType().getName();
Map<String, String> details = new HashMap<>();
details.put("dataType", paramDto);
details.put("name", name);
details.put("type", type);
details.put("class", qualifiedName);
details.put("sampleJson", sampleJson(qualifiedName, name));
inputParameters.put(name, details);
}
endpointInfo.setInputParameter(inputParameters);
} catch (Exception e) {
// Log the error and details for debugging
String msg = "Error while processing endpoint info for method: " + method.getMethod().getName();
printLog(e.getMessage(), msg);
// Return a null or default object if needed
// Depending on your specific requirements, you might want to handle this differently
return null;
}
return endpointInfo;
}
private String sampleJson(String className, String variableName) {
Class<?> clazz;
Object instance = null;
try {
clazz = Class.forName(className);
if (clazz.isEnum()) {
Object[] enumConstants = clazz.getEnumConstants();
instance = enumConstants.length > 0 ? enumConstants[0] : null;
} else if (clazz.isPrimitive() || clazz == Integer.class || clazz == Long.class || clazz == Short.class
|| clazz == Double.class || clazz == Float.class || clazz == Byte.class || clazz == Character.class
|| clazz == Boolean.class) {
instance = Array.get(Array.newInstance(clazz, 1), 0);
} else if (clazz == String.class) {
instance = "";
} else if (clazz == LocalDateTime.class) {
instance = LocalDateTime.now();
} else if (clazz == LocalDate.class) {
instance = LocalDate.now();
} else if (clazz == LocalTime.class) {
instance = LocalTime.now();
} else if (clazz == Instant.class) {
instance = Instant.now();
} else if (clazz == ZonedDateTime.class) {
instance = ZonedDateTime.now();
} else if (clazz == OffsetDateTime.class) {
instance = OffsetDateTime.now();
} else if (clazz == OffsetTime.class) {
instance = OffsetTime.now();
} else if (clazz == YearMonth.class) {
instance = YearMonth.now();
} else if (clazz == Year.class) {
instance = Year.now();
} else if (clazz == MonthDay.class) {
instance = MonthDay.now();
} else if (clazz == Duration.class) {
instance = Duration.ofSeconds(0);
} else if (clazz == Period.class) {
instance = Period.ofDays(0);
} else {
instance = clazz.getDeclaredConstructor().newInstance();
}
} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException
| ClassNotFoundException e) {
// Log the error
//printLog(e.getMessage(), "error during creating of sample json");
}
Map<String, Object> result = new HashMap<>();
result.put(variableName, instance);
return gson.toJson(result);
}
private String getParameterType(MethodParameter parameter) {
if (parameter.hasParameterAnnotation(RequestHeader.class)) {
return "header";
} else if (parameter.hasParameterAnnotation(RequestParam.class)) {
return "query";
} else if (parameter.hasParameterAnnotation(PathVariable.class)) {
return "path";
} else if (parameter.hasParameterAnnotation(RequestBody.class)) {
return "body";
}
return "unknown"; // Default type
}
private String getPayloadToPush() {
Map<Class<?>, List<EndpointInfo>> endpointList = endpointService.getEndpoints();
ServiceApiDetails serviceApiDetails = new ServiceApiDetails();
serviceApiDetails.setServiceName(userApplicationName);
serviceApiDetails.setControllerVsApis(endpointList);
String json = null;
try {
json = new Gson().toJson(serviceApiDetails);
} catch (Exception e) {
printLog(e.getMessage(), "error during payload pushing");
}
return json;
}
public void postApiInfoToInventory() throws MalformedURLException {
HttpURLConnection connection = null;
try {
String payload = getPayloadToPush();
URL url = URI.create(apiFlowBackendUrl + Constants.CODE_SCAN_INGESTION_URI).toURL();
// Logging the start of the API call
//printLog("Starting the POST request to the inventory API...", url.toString());
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(HttpRequestMethod.POST.toString());
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Connection", "close");
// Assuming accessHeaders is a Map<String, String>
for (Map.Entry<String, String> entry : accessHeaders.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
// Writing the payload
try (OutputStream os = connection.getOutputStream()) {
byte[] input = payload.getBytes("utf-8");
os.write(input, 0, input.length);
}
int responseCode = connection.getResponseCode();
// Checking and logging the result
if (responseCode == HttpURLConnection.HTTP_OK) {
//printLog("Successfully posted to the inventory API.", "");
// vikram
} else {
//printLog("Failed to post to the inventory API. Status code: ", String.valueOf(responseCode));
}
} catch (Exception e) {
// Error handling and logging
//printLog("An error occurred during the API call to the inventory.", "something went wrong");
// e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
public void printLog(String msg, String s) {
if (Boolean.TRUE.equals(logEnable)) {
System.out.println(msg + " , " + s);
}
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/scanner/EndpointInfo.java
|
package ai.apiverse.apisuite.scanner;
import lombok.Data;
import java.util.Map;
@Data
public class EndpointInfo {
private String pattern;
private String method;
private String methodDetails;
private Object returnParameter;
private Map<Object, Object> inputParameter;
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/scanner/EndpointService.java
|
package ai.apiverse.apisuite.scanner;
import lombok.Data;
import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Data
public class EndpointService {
private final List<EndpointInfo> endpoints = new ArrayList<>();
Map<Class<?>, List<EndpointInfo>> controllerVsApis = new HashMap<>();
private ApplicationContext applicationContext;
public void scanEndpoints() {
controllerVsApis.clear();
endpoints.clear();
String[] names = applicationContext.getBeanNamesForType(RequestMappingHandlerMapping.class);
RequestMappingHandlerMapping requestMappingHandlerMapping = (RequestMappingHandlerMapping) applicationContext.getBean(names[0]);
requestMappingHandlerMapping.getHandlerMethods().forEach((info, method) -> {
EndpointInfo endpointInfo = ApiScannerConfig.getInstance().getMappingInfo(info, method);
Class<?> controller = method.getBeanType();
List<EndpointInfo> apilist = controllerVsApis.getOrDefault(controller, new ArrayList<>());
apilist.add(endpointInfo);
controllerVsApis.put(controller, apilist);
endpoints.add(endpointInfo);
});
}
public Map<Class<?>, List<EndpointInfo>> getEndpoints() {
scanEndpoints();
return controllerVsApis;
}
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/scanner/ServiceApiDetails.java
|
package ai.apiverse.apisuite.scanner;
import lombok.Data;
import java.util.List;
import java.util.Map;
@Data
public class ServiceApiDetails {
private Map<Class<?>, List<EndpointInfo>> controllerVsApis;
private String serviceName;
private String team;
}
|
0
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite
|
java-sources/ai/apiverse/apipulse/1.0.20/ai/apiverse/apisuite/testController/BasicController.java
|
package ai.apiverse.apisuite.testController;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class BasicController {
@GetMapping("/hello")
public ResponseEntity<String> sayHello() {
try {
// Simulate some processing time
Thread.sleep(1000);
// Business logic
String message = "Hello, world!";
// Logging
System.out.println("Request handled successfully. Sent: " + message);
return ResponseEntity.ok(message);
} catch (InterruptedException e) {
// Error handling
System.err.println("An error occurred: " + e.getMessage());
return ResponseEntity.status(500).body("Internal server error");
}
}
@PostMapping("/hello")
public ResponseEntity<String> sayHellopost(@RequestBody String body) {
try {
// Simulate some processing time
Thread.sleep(1000);
// Business logic
String message = "Hello, world!";
// Logging
System.out.println("Request handled successfully. Sent: " + message);
return ResponseEntity.ok(message);
} catch (InterruptedException e) {
// Error handling
System.err.println("An error occurred: " + e.getMessage());
return ResponseEntity.status(500).body("Internal server error");
}
}
@GetMapping("/greet/{name}")
public ResponseEntity<String> greetUser(
@PathVariable String name,
@RequestParam(value = "age", required = false) Integer age,
@RequestParam(value = "country", required = false) String country) {
try {
// Simulate some processing time
Thread.sleep(1000);
// Business logic
StringBuilder message = new StringBuilder("Hello, " + name + "!");
if (age != null) {
message.append(" You are ").append(age).append(" years old.");
}
if (country != null) {
message.append(" You are from ").append(country).append(".");
}
// Logging
System.out.println("Request handled successfully. Sent: " + message.toString());
return ResponseEntity.ok(message.toString());
} catch (InterruptedException e) {
// Error handling
System.err.println("An error occurred: " + e.getMessage());
return ResponseEntity.status(500).body("Internal server error");
}
}
}
|
0
|
java-sources/ai/apptuit/jinsight/1.0.10/ai/apptuit/metrics
|
java-sources/ai/apptuit/jinsight/1.0.10/ai/apptuit/metrics/jinsight/Agent.java
|
/*
* Copyright 2017 Agilx, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.apptuit.metrics.jinsight;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.instrument.Instrumentation;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.function.BiConsumer;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jboss.byteman.agent.Main;
/**
* The main agent class for JInsight. A wrapper around ByteMan Agent to easy configuration and setup
*
* @author Rajiv Shivane
*/
public class Agent {
private static final Logger LOGGER = Logger.getLogger(Agent.class.getName());
private static final String BYTEMAN_JAR_RESOURCE_NAME = "META-INF/boot/byteman.jar";
private static final String BTM_SCRIPTS_RESOURCE_PATH = "META-INF/btm-scripts/jinsight.btm";
private static final String MODULE_LOADER_CLASSNAME =
"ai.apptuit.metrics.jinsight.ContextualModuleLoader";
private static final String AGENT_PARAMS = "resourcescript:" + BTM_SCRIPTS_RESOURCE_PATH
+ ",modules:" + MODULE_LOADER_CLASSNAME;
public static void premain(String agentArgs, Instrumentation instrumentation) throws Exception {
main0(agentArgs, instrumentation, (a, i) -> {
try {
if (isBciDisabled()) {
return;
}
Main.premain(a, i);
} catch (Exception e) {
throw new AgentInitializationException(e);
}
});
}
public static void agentmain(String agentArgs, Instrumentation instrumentation) throws Exception {
main0(agentArgs, instrumentation, (a, i) -> {
try {
if (isBciDisabled()) {
return;
}
Main.agentmain(a, i);
} catch (Exception e) {
throw new AgentInitializationException(e);
}
});
}
private static boolean isBciDisabled() {
return Boolean.parseBoolean(System.getenv("JINSIGHT_DISABLE_BCI"));
}
private static void main0(String agentArgs, Instrumentation instrumentation,
BiConsumer<String, Instrumentation> delegate) {
if (ClassLoader.getSystemResource(BTM_SCRIPTS_RESOURCE_PATH) == null) {
LOGGER.severe("Could not load " + BTM_SCRIPTS_RESOURCE_PATH + "."
+ "Agent will not be started.");
return;
}
try {
ConfigService.initialize();
} catch (ConfigurationException | IOException | RuntimeException e) {
LOGGER.severe(e.getMessage());
LOGGER.severe("Agent will not be started.");
return;
}
if (agentArgs != null && agentArgs.trim().length() > 0) {
agentArgs += "," + AGENT_PARAMS;
} else {
agentArgs = AGENT_PARAMS;
}
JarFile bytemanJar = createBytemanJar();
if (bytemanJar == null) {
LOGGER.severe("Could not locate: " + BYTEMAN_JAR_RESOURCE_NAME);
LOGGER.severe("Agent will not be started.");
return;
}
instrumentation.appendToBootstrapClassLoaderSearch(bytemanJar);
delegate.accept(agentArgs, instrumentation);
ConfigService configService = ConfigService.getInstance();
boolean success = RegistryService.getRegistryService().initialize();
LOGGER.info(getStartupMessage(configService, success));
}
public static String getStartupMessage(ConfigService configService, boolean initialized) {
ConfigService.ReporterType reporterType = configService.getReporterType();
StringBuilder infoMessage = new StringBuilder();
infoMessage.append(String.format("Initializing JInsight v[%s] with config "
+ "[BCI: %s] [reporter: %s] ", configService.getAgentVersion(),
isBciDisabled() ? "Disabled" : "Enabled", reporterType));
if (reporterType == ConfigService.ReporterType.APPTUIT) {
infoMessage.append(String.format("[mode: %s ] [frequency: %s seconds]",
configService.getReportingMode(), (configService.getReportingFrequency() / 1000)));
} else if (reporterType == ConfigService.ReporterType.PROMETHEUS) {
infoMessage.append(String.format("[port: %s] [metrics-path: %s ]",
configService.getPrometheusPort(), configService.getPrometheusMetricsPath()));
} else {
throw new IllegalStateException();
}
infoMessage.append(initialized ? ": SUCCESSFUL" : ": FAILED");
return infoMessage.toString();
}
private static JarFile createBytemanJar() {
ClassLoader classLoader = Agent.class.getClassLoader();
InputStream bytemanStream = classLoader.getResourceAsStream(BYTEMAN_JAR_RESOURCE_NAME);
if (bytemanStream == null) {
return null;
}
try {
//TODO Improve. Can we skip extraction if the hash matches?
File bytemanJar = File.createTempFile("byteman", ".jar");
bytemanJar.deleteOnExit();
Files.copy(bytemanStream, bytemanJar.toPath(), StandardCopyOption.REPLACE_EXISTING);
return new JarFile(bytemanJar);
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Error extracting byteman.jar.", e);
}
return null;
}
private static class AgentInitializationException extends RuntimeException {
public AgentInitializationException(Exception e) {
super(e);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.