use of org.apache.commons.codec.DecoderException in project spring-security-oauth by spring-projects.
the class CoreOAuthConsumerSupport method getTokenFromProvider.
/**
* Get the consumer token with the given parameters and URL. The determination of whether the retrieved token
* is an access token depends on whether a request token is provided.
*
* @param details The resource details.
* @param tokenURL The token URL.
* @param httpMethod The http method.
* @param requestToken The request token, or null if none.
* @param additionalParameters The additional request parameter.
* @return The token.
*/
protected OAuthConsumerToken getTokenFromProvider(ProtectedResourceDetails details, URL tokenURL, String httpMethod, OAuthConsumerToken requestToken, Map<String, String> additionalParameters) {
boolean isAccessToken = requestToken != null;
if (!isAccessToken) {
// create an empty token to make a request for a new unauthorized request token.
requestToken = new OAuthConsumerToken();
}
TreeMap<String, String> requestHeaders = new TreeMap<String, String>();
if ("POST".equalsIgnoreCase(httpMethod)) {
requestHeaders.put("Content-Type", "application/x-www-form-urlencoded");
}
InputStream inputStream = readResource(details, tokenURL, httpMethod, requestToken, additionalParameters, requestHeaders);
String tokenInfo;
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = inputStream.read(buffer);
while (len >= 0) {
out.write(buffer, 0, len);
len = inputStream.read(buffer);
}
tokenInfo = new String(out.toByteArray(), "UTF-8");
} catch (IOException e) {
throw new OAuthRequestFailedException("Unable to read the token.", e);
}
StringTokenizer tokenProperties = new StringTokenizer(tokenInfo, "&");
Map<String, String> tokenPropertyValues = new TreeMap<String, String>();
while (tokenProperties.hasMoreElements()) {
try {
String tokenProperty = (String) tokenProperties.nextElement();
int equalsIndex = tokenProperty.indexOf('=');
if (equalsIndex > 0) {
String propertyName = OAuthCodec.oauthDecode(tokenProperty.substring(0, equalsIndex));
String propertyValue = OAuthCodec.oauthDecode(tokenProperty.substring(equalsIndex + 1));
tokenPropertyValues.put(propertyName, propertyValue);
} else {
tokenProperty = OAuthCodec.oauthDecode(tokenProperty);
tokenPropertyValues.put(tokenProperty, null);
}
} catch (DecoderException e) {
throw new OAuthRequestFailedException("Unable to decode token parameters.");
}
}
String tokenValue = tokenPropertyValues.remove(OAuthProviderParameter.oauth_token.toString());
if (tokenValue == null) {
throw new OAuthRequestFailedException("OAuth provider failed to return a token.");
}
String tokenSecret = tokenPropertyValues.remove(OAuthProviderParameter.oauth_token_secret.toString());
if (tokenSecret == null) {
throw new OAuthRequestFailedException("OAuth provider failed to return a token secret.");
}
OAuthConsumerToken consumerToken = new OAuthConsumerToken();
consumerToken.setValue(tokenValue);
consumerToken.setSecret(tokenSecret);
consumerToken.setResourceId(details.getId());
consumerToken.setAccessToken(isAccessToken);
if (!tokenPropertyValues.isEmpty()) {
consumerToken.setAdditionalParameters(tokenPropertyValues);
}
return consumerToken;
}
use of org.apache.commons.codec.DecoderException in project incubator-gobblin by apache.
the class SchemaRegistryVersionWriter method writeSchemaVersioningInformation.
@Override
public void writeSchemaVersioningInformation(Schema schema, DataOutputStream outputStream) throws IOException {
String schemaId = this.schemaId.isPresent() ? this.schemaId.get() : this.getIdForSchema(schema);
outputStream.writeByte(KafkaAvroSchemaRegistry.MAGIC_BYTE);
try {
outputStream.write(Hex.decodeHex(schemaId.toCharArray()));
} catch (DecoderException exception) {
throw new IOException(exception);
}
}
use of org.apache.commons.codec.DecoderException in project archiva by apache.
the class RssFeedServlet method isAllowed.
/**
* Basic authentication.
*
* @param req
* @param repositoryId TODO
* @param groupId TODO
* @param artifactId TODO
* @return
*/
private boolean isAllowed(HttpServletRequest req, String repositoryId, String groupId, String artifactId) throws UserNotFoundException, AccountLockedException, AuthenticationException, MustChangePasswordException, UnauthorizedException {
String auth = req.getHeader("Authorization");
List<String> repoIds = new ArrayList<>();
if (repositoryId != null) {
repoIds.add(repositoryId);
} else if (artifactId != null && groupId != null) {
if (auth != null) {
if (!auth.toUpperCase().startsWith("BASIC ")) {
return false;
}
Decoder dec = new Base64();
String usernamePassword = "";
try {
usernamePassword = new String((byte[]) dec.decode(auth.substring(6).getBytes()));
} catch (DecoderException ie) {
log.warn("Error decoding username and password: {}", ie.getMessage());
}
if (usernamePassword == null || usernamePassword.trim().equals("")) {
repoIds = getObservableRepos(UserManager.GUEST_USERNAME);
} else {
String[] userCredentials = usernamePassword.split(":");
repoIds = getObservableRepos(userCredentials[0]);
}
} else {
repoIds = getObservableRepos(UserManager.GUEST_USERNAME);
}
} else {
return false;
}
for (String repoId : repoIds) {
try {
AuthenticationResult result = httpAuth.getAuthenticationResult(req, null);
SecuritySession securitySession = httpAuth.getSecuritySession(req.getSession(true));
if (//
servletAuth.isAuthenticated(req, result) && //
servletAuth.isAuthorized(//
req, //
securitySession, //
repoId, ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS)) {
return true;
}
} catch (AuthorizationException e) {
log.debug("AuthorizationException for repoId: {}", repoId);
} catch (UnauthorizedException e) {
log.debug("UnauthorizedException for repoId: {}", repoId);
}
}
throw new UnauthorizedException("Access denied.");
}
use of org.apache.commons.codec.DecoderException in project nakadi by zalando.
the class ClosedConnectionsCrutch method getCurrentConnections.
@VisibleForTesting
Map<ConnectionInfo, ConnectionState> getCurrentConnections(final InputStream in) throws IOException {
final Map<ConnectionInfo, ConnectionState> connectionToState = new HashMap<>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
// /proc/net/tcp[6]
// idx, local_address, remote_address, status, ...
// Skip heading
reader.readLine();
String line;
while (null != (line = reader.readLine())) {
final StringTokenizer tokenizer = new StringTokenizer(line);
// skip id
tokenizer.nextToken();
try {
// read local address
final String[] localAddress = tokenizer.nextToken().split(":");
final int localPort = Integer.parseInt(localAddress[1], 16);
if (localPort != port) {
continue;
}
// read remote address
final String[] remoteAddressPair = tokenizer.nextToken().split(":");
final InetAddress[] remoteAddresses = restoreAddresses(remoteAddressPair[0]);
final int remotePort = Integer.parseInt(remoteAddressPair[1], 16);
// read connection state
final ConnectionState connectionState = ConnectionState.fromCode(tokenizer.nextToken());
Stream.of(remoteAddresses).map(address -> new ConnectionInfo(address, remotePort)).forEach(info -> connectionToState.put(info, connectionState));
} catch (final DecoderException | RuntimeException ex) {
LOG.error("Failed to parse line, skipping: " + line, ex);
}
}
}
return connectionToState;
}
use of org.apache.commons.codec.DecoderException in project ovirt-engine by oVirt.
the class GetUnregisteredDiskQuery method executeQueryCommand.
@Override
protected void executeQueryCommand() {
Guid storagePoolId = getParameters().getStoragePoolId();
Guid storageDomainId = getParameters().getStorageDomainId();
Guid diskId = getParameters().getDiskId();
StorageDomain storageDomain = storageDomainDao.get(storageDomainId);
if (storageDomain == null) {
getQueryReturnValue().setExceptionString(EngineMessage.STORAGE_DOMAIN_DOES_NOT_EXIST.toString());
getQueryReturnValue().setSucceeded(false);
return;
}
if (storageDomain.getStorageType().isCinderDomain()) {
QueryReturnValue returnValue = runInternalQuery(QueryType.GetUnregisteredCinderDiskByIdAndStorageDomainId, new GetCinderEntityByStorageDomainIdParameters(diskId, getParameters().getStorageDomainId()));
setReturnValue(returnValue.getReturnValue());
return;
}
// Now get the list of volumes for each new image.
StoragePoolDomainAndGroupIdBaseVDSCommandParameters getVolumesParameters = new StoragePoolDomainAndGroupIdBaseVDSCommandParameters(storagePoolId, storageDomainId, diskId);
VDSReturnValue volumesListReturn = runVdsCommand(VDSCommandType.GetVolumesList, getVolumesParameters);
if (!volumesListReturn.getSucceeded()) {
getQueryReturnValue().setExceptionString(volumesListReturn.getExceptionString());
getQueryReturnValue().setSucceeded(false);
return;
}
@SuppressWarnings("unchecked") List<Guid> volumesList = (List<Guid>) volumesListReturn.getReturnValue();
// image. If there are multiple volumes, skip the image and move on to the next.
if (volumesList.size() != 1) {
getQueryReturnValue().setSucceeded(false);
return;
}
Guid volumeId = volumesList.get(0);
// Get the information about the volume from VDSM.
GetImageInfoVDSCommandParameters imageInfoParameters = new GetImageInfoVDSCommandParameters(storagePoolId, storageDomainId, diskId, volumeId);
VDSReturnValue imageInfoReturn = runVdsCommand(VDSCommandType.GetImageInfo, imageInfoParameters);
if (!imageInfoReturn.getSucceeded()) {
getQueryReturnValue().setExceptionString(imageInfoReturn.getExceptionString());
getQueryReturnValue().setSucceeded(false);
return;
}
DiskImage newDiskImage = (DiskImage) imageInfoReturn.getReturnValue();
if (!fetchQcowCompat(storagePoolId, storageDomainId, diskId, volumeId, newDiskImage)) {
getQueryReturnValue().setSucceeded(false);
return;
}
if (StringUtils.isNotEmpty(newDiskImage.getDescription())) {
try {
metadataDiskDescriptionHandler.enrichDiskByJsonDescription(newDiskImage.getDescription(), newDiskImage);
} catch (IOException | DecoderException e) {
log.warn("Could not parse the description ({}) of disk ID '{}'. The description is expected to be in " + "JSON format.", newDiskImage.getDescription(), newDiskImage.getId());
log.debug("Exception while parsing JSON for disk", e);
}
}
newDiskImage.setStoragePoolId(storagePoolId);
getQueryReturnValue().setReturnValue(newDiskImage);
getQueryReturnValue().setSucceeded(true);
}
Aggregations