Search in sources :

Example 26 with DecoderException

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;
}
Also used : OAuthRequestFailedException(org.springframework.security.oauth.consumer.OAuthRequestFailedException) OAuthConsumerToken(org.springframework.security.oauth.consumer.OAuthConsumerToken) DecoderException(org.apache.commons.codec.DecoderException)

Example 27 with DecoderException

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);
    }
}
Also used : DecoderException(org.apache.commons.codec.DecoderException) IOException(java.io.IOException)

Example 28 with DecoderException

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.");
}
Also used : DecoderException(org.apache.commons.codec.DecoderException) Base64(org.apache.commons.codec.binary.Base64) AuthorizationException(org.apache.archiva.redback.authorization.AuthorizationException) SecuritySession(org.apache.archiva.redback.system.SecuritySession) ArrayList(java.util.ArrayList) UnauthorizedException(org.apache.archiva.redback.authorization.UnauthorizedException) Decoder(org.apache.commons.codec.Decoder) AuthenticationResult(org.apache.archiva.redback.authentication.AuthenticationResult)

Example 29 with DecoderException

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;
}
Also used : LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ArrayUtils(org.apache.commons.lang3.ArrayUtils) HashMap(java.util.HashMap) Hex(org.apache.commons.codec.binary.Hex) Scheduled(org.springframework.scheduling.annotation.Scheduled) ArrayList(java.util.ArrayList) BooleanSupplier(java.util.function.BooleanSupplier) Value(org.springframework.beans.factory.annotation.Value) InetAddress(java.net.InetAddress) HashSet(java.util.HashSet) Meter(com.codahale.metrics.Meter) HttpServletRequest(javax.servlet.http.HttpServletRequest) StringTokenizer(java.util.StringTokenizer) Map(java.util.Map) MetricRegistry(com.codahale.metrics.MetricRegistry) ImmutableSet(com.google.common.collect.ImmutableSet) Logger(org.slf4j.Logger) DecoderException(org.apache.commons.codec.DecoderException) Set(java.util.Set) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) InputStreamReader(java.io.InputStreamReader) UnknownHostException(java.net.UnknownHostException) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) Inet6Address(java.net.Inet6Address) Component(org.springframework.stereotype.Component) List(java.util.List) Stream(java.util.stream.Stream) VisibleForTesting(com.google.common.annotations.VisibleForTesting) BufferedReader(java.io.BufferedReader) InetAddresses(com.google.common.net.InetAddresses) InputStream(java.io.InputStream) InputStreamReader(java.io.InputStreamReader) HashMap(java.util.HashMap) DecoderException(org.apache.commons.codec.DecoderException) StringTokenizer(java.util.StringTokenizer) BufferedReader(java.io.BufferedReader) InetAddress(java.net.InetAddress) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 30 with DecoderException

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);
}
Also used : GetImageInfoVDSCommandParameters(org.ovirt.engine.core.common.vdscommands.GetImageInfoVDSCommandParameters) Guid(org.ovirt.engine.core.compat.Guid) StoragePoolDomainAndGroupIdBaseVDSCommandParameters(org.ovirt.engine.core.common.vdscommands.StoragePoolDomainAndGroupIdBaseVDSCommandParameters) IOException(java.io.IOException) GetCinderEntityByStorageDomainIdParameters(org.ovirt.engine.core.common.action.GetCinderEntityByStorageDomainIdParameters) VDSReturnValue(org.ovirt.engine.core.common.vdscommands.VDSReturnValue) DecoderException(org.apache.commons.codec.DecoderException) StorageDomain(org.ovirt.engine.core.common.businessentities.StorageDomain) QueryReturnValue(org.ovirt.engine.core.common.queries.QueryReturnValue) List(java.util.List) DiskImage(org.ovirt.engine.core.common.businessentities.storage.DiskImage)

Aggregations

DecoderException (org.apache.commons.codec.DecoderException)41 IOException (java.io.IOException)16 CharSequenceX (com.samourai.wallet.util.CharSequenceX)8 MnemonicException (org.bitcoinj.crypto.MnemonicException)8 JSONException (org.json.JSONException)7 DecryptionException (com.samourai.wallet.crypto.DecryptionException)6 ArrayList (java.util.ArrayList)6 Intent (android.content.Intent)5 ProgressDialog (android.app.ProgressDialog)4 HD_Wallet (com.samourai.wallet.hd.HD_Wallet)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 HashMap (java.util.HashMap)4 List (java.util.List)4 BufferedReader (java.io.BufferedReader)3 File (java.io.File)3 FileNotFoundException (java.io.FileNotFoundException)3 ByteBuffer (java.nio.ByteBuffer)3 Map (java.util.Map)3 Cipher (javax.crypto.Cipher)3 AddressFormatException (org.bitcoinj.core.AddressFormatException)3