Example usage for java.util Base64 getEncoder

List of usage examples for java.util Base64 getEncoder

Introduction

In this page you can find the example usage for java.util Base64 getEncoder.

Prototype

public static Encoder getEncoder() 

Source Link

Document

Returns a Encoder that encodes using the Basic type base64 encoding scheme.

Usage

From source file:it.greenvulcano.gvesb.datahandling.dbo.utils.StandardRowSetBuilder.java

public int build(Document doc, String id, ResultSet rs, Set<Integer> keyField,
        Map<String, FieldFormatter> fieldNameToFormatter, Map<String, FieldFormatter> fieldIdToFormatter)
        throws Exception {
    if (rs == null) {
        return 0;
    }/*from  www  . j  a  v  a 2s  . c  o m*/
    int rowCounter = 0;
    Element docRoot = doc.getDocumentElement();
    ResultSetMetaData metadata = rs.getMetaData();
    FieldFormatter[] fFormatters = buildFormatterArray(metadata, fieldNameToFormatter, fieldIdToFormatter);

    boolean noKey = ((keyField == null) || keyField.isEmpty());

    //boolean isNull = false;
    Element data = null;
    Element row = null;
    Element col = null;
    Text text = null;
    String textVal = null;
    String precKey = null;
    String colKey = null;
    Map<String, String> keyAttr = new HashMap<String, String>();
    while (rs.next()) {
        if (rowCounter % 10 == 0) {
            ThreadUtils.checkInterrupted(getClass().getSimpleName(), name, logger);
        }
        row = parser.createElement(doc, AbstractDBO.ROW_NAME);

        parser.setAttribute(row, AbstractDBO.ID_NAME, id);
        for (int j = 1; j <= metadata.getColumnCount(); j++) {
            FieldFormatter fF = fFormatters[j];

            //isNull = false;
            col = parser.createElement(doc, AbstractDBO.COL_NAME);
            switch (metadata.getColumnType(j)) {
            case Types.DATE: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DATE_TYPE);
                java.sql.Date dateVal = rs.getDate(j);
                textVal = processDateTime(col, fF, dateVal, AbstractDBO.DEFAULT_DATE_FORMAT);
            }
                break;
            case Types.TIME: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.TIME_TYPE);
                java.sql.Time dateVal = rs.getTime(j);
                textVal = processDateTime(col, fF, dateVal, AbstractDBO.DEFAULT_TIME_FORMAT);
            }
                break;
            case Types.TIMESTAMP: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.TIMESTAMP_TYPE);
                Timestamp dateVal = rs.getTimestamp(j);
                textVal = processDateTime(col, fF, dateVal, AbstractDBO.DEFAULT_DATE_FORMAT);
            }
                break;
            case Types.DOUBLE: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                double numVal = rs.getDouble(j);
                textVal = processDouble(col, fF, numVal);
            }
                break;
            case Types.FLOAT:
            case Types.REAL: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.FLOAT_TYPE);
                float numVal = rs.getFloat(j);
                textVal = processDouble(col, fF, numVal);
            }
                break;
            case Types.BIGINT: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.BIGINT_TYPE);
                long numVal = rs.getLong(j);
                parser.setAttribute(col, AbstractDBO.NULL_NAME, "false");
                textVal = String.valueOf(numVal);
            }
                break;
            case Types.INTEGER: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.INTEGER_TYPE);
                int numVal = rs.getInt(j);
                parser.setAttribute(col, AbstractDBO.NULL_NAME, "false");
                textVal = String.valueOf(numVal);
            }
                break;
            case Types.SMALLINT:
            case Types.TINYINT: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.SMALLINT_TYPE);
                short numVal = rs.getShort(j);
                parser.setAttribute(col, AbstractDBO.NULL_NAME, "false");
                textVal = String.valueOf(numVal);
            }
                break;
            case Types.NUMERIC:
            case Types.DECIMAL: {
                BigDecimal bigdecimal = rs.getBigDecimal(j);
                boolean isNull = bigdecimal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    if (metadata.getScale(j) > 0) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DECIMAL_TYPE);
                    } else {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE);
                    }
                    textVal = "";
                } else {
                    if (fF != null) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DECIMAL_TYPE);
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, fF.getNumberFormat());
                        parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, fF.getGroupSeparator());
                        parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, fF.getDecSeparator());
                        textVal = fF.formatNumber(bigdecimal);
                    } else if (metadata.getScale(j) > 0) {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DECIMAL_TYPE);
                        parser.setAttribute(col, AbstractDBO.FORMAT_NAME, numberFormat);
                        parser.setAttribute(col, AbstractDBO.GRP_SEPARATOR_NAME, groupSeparator);
                        parser.setAttribute(col, AbstractDBO.DEC_SEPARATOR_NAME, decSeparator);
                        textVal = numberFormatter.format(bigdecimal);
                    } else {
                        parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NUMERIC_TYPE);
                        textVal = bigdecimal.toString();
                    }
                }
            }
                break;
            case Types.BOOLEAN: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.BOOLEAN_TYPE);
                boolean bVal = rs.getBoolean(j);
                parser.setAttribute(col, AbstractDBO.NULL_NAME, "false");
                textVal = String.valueOf(bVal);
            }
                break;
            case Types.SQLXML: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.XML_TYPE);
                SQLXML xml = rs.getSQLXML(j);
                boolean isNull = xml == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                } else {
                    textVal = xml.getString();
                }
            }
                break;
            case Types.NCHAR:
            case Types.NVARCHAR: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.NSTRING_TYPE);
                textVal = rs.getNString(j);
                if (textVal == null) {
                    textVal = "";
                }
            }
                break;
            case Types.CHAR:
            case Types.VARCHAR: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.STRING_TYPE);
                textVal = rs.getString(j);
                boolean isNull = textVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                }
            }
                break;
            case Types.NCLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.LONG_NSTRING_TYPE);
                NClob clob = rs.getNClob(j);
                if (clob != null) {
                    Reader is = clob.getCharacterStream();
                    StringWriter str = new StringWriter();

                    IOUtils.copy(is, str);
                    is.close();
                    textVal = str.toString();
                } else {
                    textVal = "";
                }
            }
                break;
            case Types.CLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.LONG_STRING_TYPE);
                Clob clob = rs.getClob(j);
                if (clob != null) {
                    Reader is = clob.getCharacterStream();
                    StringWriter str = new StringWriter();

                    IOUtils.copy(is, str);
                    is.close();
                    textVal = str.toString();
                } else {
                    textVal = "";
                }
            }
                break;
            case Types.BLOB: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.BASE64_TYPE);
                Blob blob = rs.getBlob(j);
                boolean isNull = blob == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                } else {
                    InputStream is = blob.getBinaryStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    IOUtils.copy(is, baos);
                    is.close();
                    try {
                        byte[] buffer = Arrays.copyOf(baos.toByteArray(), (int) blob.length());
                        textVal = Base64.getEncoder().encodeToString(buffer);
                    } catch (SQLFeatureNotSupportedException exc) {
                        textVal = Base64.getEncoder().encodeToString(baos.toByteArray());
                    }
                }
            }
                break;
            default: {
                parser.setAttribute(col, AbstractDBO.TYPE_NAME, AbstractDBO.DEFAULT_TYPE);
                textVal = rs.getString(j);
                boolean isNull = textVal == null;
                parser.setAttribute(col, AbstractDBO.NULL_NAME, String.valueOf(isNull));
                if (isNull) {
                    textVal = "";
                }
            }
            }
            if (textVal != null) {
                text = doc.createTextNode(textVal);
                col.appendChild(text);
            }
            if (!noKey && keyField.contains(new Integer(j))) {
                if (textVal != null) {
                    if (colKey == null) {
                        colKey = textVal;
                    } else {
                        colKey += "##" + textVal;
                    }
                    keyAttr.put("key_" + j, textVal);
                }
            } else {
                row.appendChild(col);
            }
        }
        if (noKey) {
            if (data == null) {
                data = parser.createElement(doc, AbstractDBO.DATA_NAME);
                parser.setAttribute(data, AbstractDBO.ID_NAME, id);
            }
        } else if ((colKey != null) && !colKey.equals(precKey)) {
            if (data != null) {
                docRoot.appendChild(data);
            }
            data = parser.createElement(doc, AbstractDBO.DATA_NAME);
            parser.setAttribute(data, AbstractDBO.ID_NAME, id);
            for (Entry<String, String> keyAttrEntry : keyAttr.entrySet()) {
                parser.setAttribute(data, keyAttrEntry.getKey(), keyAttrEntry.getValue());
            }
            keyAttr.clear();
            precKey = colKey;
        }
        colKey = null;
        data.appendChild(row);
        rowCounter++;
    }
    if (data != null) {
        docRoot.appendChild(data);
    }

    return rowCounter;
}

From source file:org.wso2.carbon.apimgt.core.impl.LogInKeyManagerImpl.java

@Override
public OAuthApplicationInfo retrieveApplication(String consumerKey) throws KeyManagementException {

    APIUtils.logDebug("Trying to retrieve OAuth application for consumer key :" + consumerKey, log);
    OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
    URL url;// w w  w .j  ava 2 s  .  c  om
    HttpURLConnection urlConn = null;
    try {
        createSSLConnection();
        // Calling DCR endpoint of IS using consumer key
        String dcrEndpoint = getKeyManagerEndPoint("/identity/connect/register/") + consumerKey;
        /* System.getProperty("dcrEndpoint", "https://localhost:9443/identity/connect/register/" +
         consumerKey);*/
        url = new URL(dcrEndpoint);
        urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setDoOutput(true);
        urlConn.setRequestMethod("GET");
        urlConn.setRequestProperty("content-type", "application/json");
        String clientEncoded = Base64.getEncoder().encodeToString((System.getProperty("systemUsername", "admin")
                + ":" + System.getProperty("systemUserPwd", "admin")).getBytes(StandardCharsets.UTF_8));
        urlConn.setRequestProperty("Authorization", "Basic " + clientEncoded); //temp fix
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) { //If the DCR call is success
            String responseStr = new String(IOUtils.toByteArray(urlConn.getInputStream()), "UTF-8");
            JsonParser parser = new JsonParser();
            JsonObject jObj = parser.parse(responseStr).getAsJsonObject();
            String consumerSecret = jObj.getAsJsonPrimitive(KeyManagerConstants.OAUTH_CLIENT_SECRET)
                    .getAsString();
            String clientName = jObj.getAsJsonPrimitive(KeyManagerConstants.OAUTH_CLIENT_NAME).getAsString();
            String grantTypes = "";
            if (jObj.has(KeyManagerConstants.OAUTH_CLIENT_GRANTS)) {
                grantTypes = jObj.getAsJsonArray(KeyManagerConstants.OAUTH_CLIENT_GRANTS).getAsString();
            }

            oAuthApplicationInfo.setClientName(clientName);
            oAuthApplicationInfo.setClientId(consumerKey);
            oAuthApplicationInfo.setClientSecret(consumerSecret);
            oAuthApplicationInfo.setGrantTypes(Arrays.asList(grantTypes.split(",")));
            oAuthApplicationInfo.addParameter(KeyManagerConstants.VALIDITY_PERIOD, "3600");

        } else { //If DCR call fails
            throw new KeyManagementException(
                    "Error while getting oauth application info for key : " + consumerKey,
                    ExceptionCodes.OAUTH2_APP_RETRIEVAL_FAILED);
        }
    } catch (IOException e) {
        String errorMsg = "Error while getting application with key : " + consumerKey;
        log.error(errorMsg, e);
        throw new KeyManagementException(errorMsg, e, ExceptionCodes.OAUTH2_APP_RETRIEVAL_FAILED);
    } catch (JsonSyntaxException e) {
        String errorMsg = "Error while processing the response returned from DCR endpoint.Can not find"
                + " OAuth application : " + consumerKey;
        log.error(errorMsg, e, ExceptionCodes.OAUTH2_APP_RETRIEVAL_FAILED);
        throw new KeyManagementException(errorMsg, ExceptionCodes.OAUTH2_APP_RETRIEVAL_FAILED);
    } catch (NoSuchAlgorithmException | java.security.KeyManagementException e) {
        String errorMsg = "Error while connecting to the DCR endpoint.Can not retrieve the"
                + " OAuth application.";
        log.error(errorMsg, e, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
        throw new KeyManagementException(errorMsg, ExceptionCodes.OAUTH2_APP_CREATION_FAILED);
    } finally {
        if (urlConn != null) {
            urlConn.disconnect();
        }
    }

    /*} TO-DO-Add logic to exception handling in retrieving oauth2 application */
    //}
    return oAuthApplicationInfo;
}

From source file:com.viettel.util.doc.DocsUtility.java

public String getBase64Word() throws IOException {
    String pathFile = saveToWord();
    try (InputStream is = new FileInputStream(pathFile)) {
        String dataFile = Base64.getEncoder().encodeToString(IOUtils.toByteArray(is));
        new File(pathFile).delete();
        return dataFile;
    }/*from  w  w  w. j a  va  2 s. c o m*/
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditorTest.java

License:asdf

@Test
public void testAddKeyLocal() throws KeystoreEditor.KeystoreEditorException, IOException {
    KeystoreEditor keystoreEditor = new KeystoreEditor();
    FileInputStream fileInputStream = new FileInputStream(localhostCrtFile);
    byte[] crtBytes = IOUtils.toByteArray(fileInputStream);
    IOUtils.closeQuietly(fileInputStream);
    keystoreEditor.addPrivateKey("localhost", password, "", Base64.getEncoder().encodeToString(crtBytes),
            KeystoreEditor.PEM_TYPE, localhostCrtFile.toString());
    List<Map<String, Object>> keystore = keystoreEditor.getKeystore();
    Assert.assertThat(keystore.size(), Is.is(1));

    List<Map<String, Object>> truststore = keystoreEditor.getTruststore();
    Assert.assertThat(truststore.size(), Is.is(0));

    keystoreEditor = new KeystoreEditor();
    fileInputStream = new FileInputStream(localhostKeyFile);
    byte[] keyBytes = IOUtils.toByteArray(fileInputStream);
    IOUtils.closeQuietly(fileInputStream);
    keystoreEditor.addPrivateKey("localhost", password, "", Base64.getEncoder().encodeToString(keyBytes), "",
            localhostKeyFile.toString());
    keystore = keystoreEditor.getKeystore();
    Assert.assertThat(keystore.size(), Is.is(1));
    Assert.assertThat((String) keystore.get(0).get("alias"), Is.is("localhost"));

    truststore = keystoreEditor.getTruststore();
    Assert.assertThat(truststore.size(), Is.is(0));
}

From source file:org.iexhub.connectors.PIXManager.java

/**
 * @param queryText//from  w w  w. j a  v a2 s  .co  m
 * @param patientId
 * @throws IOException
 */
private void logIti45AuditMsg(String queryText, String patientId) throws IOException {
    String logMsg = FileUtils.readFileToString(new File(iti45AuditMsgTemplate));

    // Substitutions...
    patientId = patientId.replace("'", "");
    patientId = patientId.replace("&", "&amp;");

    DateTime now = new DateTime(DateTimeZone.UTC);
    DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
    logMsg = logMsg.replace("$DateTime$", fmt.print(now));

    logMsg = logMsg.replace("$AltUserId$", "IExHub");

    logMsg = logMsg.replace("$IexhubIpAddress$", InetAddress.getLocalHost().getHostAddress());

    logMsg = logMsg.replace("$IexhubUserId$", "http://" + InetAddress.getLocalHost().getCanonicalHostName());

    logMsg = logMsg.replace("$DestinationIpAddress$", PIXManager.endpointUri);

    logMsg = logMsg.replace("$DestinationUserId$", "IExHub");

    // Query text must be Base64 encoded...
    logMsg = logMsg.replace("$PixQueryMtom$", Base64.getEncoder().encodeToString(queryText.getBytes()));

    logMsg = logMsg.replace("$PatientIdMtom$", Base64.getEncoder().encodeToString(patientId.getBytes()));

    logMsg = logMsg.replace("$PatientId$", patientId);

    if (logSyslogAuditMsgsLocally) {
        log.info(logMsg);
    }

    if ((sysLogConfig == null) || (iti45AuditMsgTemplate == null)) {
        return;
    }

    // Log the syslog message and close connection
    Syslog.getInstance("sslTcp").info(logMsg);
    Syslog.getInstance("sslTcp").flush();
}

From source file:bioLockJ.module.agent.MailAgent.java

private static String base64Encode(final byte[] bytes) {
    return Base64.getEncoder().encodeToString(bytes);
}

From source file:org.wso2.is.portal.user.client.api.ChallengeQuestionManagerClientServiceImpl.java

private String encodeChallengeQuestionSetId(String questionSetId) {
    return new String(Base64.getEncoder().encode(questionSetId.getBytes(Charset.forName("UTF-8"))),
            Charset.forName("UTF-8"));
}

From source file:org.xframium.integrations.alm.ALMRESTConnection.java

/**
 * Allows the user to login to ALM using the specified authentication point
 *
 * @param loginUrl            to authenticate at
 * @param username the username//from   ww w  .  j  ava2 s  . com
 * @param password the password
 * @return true on operation success, false otherwise
 * @throws Exception             Logging in to our system is standard http login (basic
 *             authentication), where one must store the returned cookies
 *             for further use.
 */
private boolean login(String loginUrl, String username, String password) throws Exception {

    // create a string that lookes like:
    // "Basic ((username:password)<as bytes>)<64encoded>"
    byte[] credBytes = (username + ":" + password).getBytes();
    String credEncodedString = "Basic " + new String(Base64.getEncoder().encode(credBytes));

    Map<String, String> map = new HashMap<String, String>();
    map.put("Authorization", credEncodedString);

    log.info(map);

    ALMResponse response = httpGet(loginUrl, null, map);

    boolean ret = response.getStatusCode() == HttpURLConnection.HTTP_OK;

    if (ret) {
        Map<String, String> requestHeaders = new HashMap<String, String>();

        // As can be seen in the implementation below, creating an entity
        // is simply posting its xml into the correct collection.
        response = httpPost(buildUrl("rest/site-session"), null, requestHeaders);
    }

    return ret;
}

From source file:com.streamsets.pipeline.stage.bigquery.destination.BigQueryTarget.java

/**
 * Convert the sdc Field to an object for row content
 *//*from w  w w .  ja v a 2  s . c o m*/
private Object getValueFromField(String fieldPath, Field field) {
    LOG.trace("Visiting Field Path '{}' of type '{}'", fieldPath, field.getType());
    switch (field.getType()) {
    case LIST:
        //REPEATED
        List<Field> listField = field.getValueAsList();
        //Convert the list to map with indices as key and Field as value (Map<Integer, Field>)
        Map<Integer, Field> fields = IntStream.range(0, listField.size()).boxed()
                .collect(Collectors.toMap(Function.identity(), listField::get));
        //filter map to remove fields with null value
        fields = fields.entrySet().stream().filter(e -> e.getValue().getValue() != null)
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        //now use the map index to generate field path and generate object for big query write
        return fields.entrySet().stream()
                .map(e -> getValueFromField(fieldPath + "[" + e.getKey() + "]", e.getValue()))
                .collect(Collectors.toList());
    case MAP:
    case LIST_MAP:
        //RECORD
        return field.getValueAsMap().entrySet().stream().filter(me -> me.getValue().getValue() != null)
                .collect(Collectors.toMap(Map.Entry::getKey,
                        e -> getValueFromField(fieldPath + "/" + e.getKey(), e.getValue())));
    case DATE:
        return dateFormat.format(field.getValueAsDate());
    case TIME:
        return timeFormat.format(field.getValueAsTime());
    case DATETIME:
        return dateTimeFormat.format(field.getValueAsDatetime());
    case BYTE_ARRAY:
        return Base64.getEncoder().encodeToString(field.getValueAsByteArray());
    case DECIMAL:
    case BYTE:
    case CHAR:
    case FILE_REF:
        throw new IllegalArgumentException(
                Utils.format(Errors.BIGQUERY_12.getMessage(), fieldPath, field.getType()));
    default:
        //Boolean -> Map to Boolean in big query
        //Float, Double -> Map to Float in big query
        //String -> maps to String in big query
        //Short, Integer, Long -> Map to integer in big query
        return field.getValue();
    }
}

From source file:org.fenixedu.bennu.oauth.OAuthServletTest.java

@Test
public void testWrongTokenTypeInHeader() {

    MockHttpServletRequest req = new MockHttpServletRequest();
    MockHttpServletResponse res = new MockHttpServletResponse();
    Authenticate.unmock();//  w  w  w  .j  ava 2 s  .  c o  m

    ExternalApplication externalApp = new ExternalApplication();
    externalApp.setAuthor(user1);
    externalApp.setName("Test External Application");
    externalApp.setDescription("This is a test external application");
    externalApp.setRedirectUrl("http://test.url/callback");
    externalApp.addScopes(externalApplicationScope);

    ApplicationUserSession applicationUserSession = new ApplicationUserSession();
    applicationUserSession.setCode("fenixedu");

    ApplicationUserAuthorization applicationUserAuthorization = new ApplicationUserAuthorization(user1,
            externalApp);
    applicationUserAuthorization.addSession(applicationUserSession);
    externalApp.addApplicationUserAuthorization(applicationUserAuthorization);

    String clientSecret = externalApp.getExternalId() + ":" + externalApp.getSecret();
    req.addHeader(HttpHeaders.AUTHORIZATION,
            "Basic " + Base64.getEncoder().encodeToString(clientSecret.getBytes(StandardCharsets.UTF_8)));
    req.addParameter(REDIRECT_URI, externalApp.getRedirectUrl());
    req.addParameter(CODE, applicationUserSession.getCode());
    req.addParameter(GRANT_TYPE, GRANT_TYPE_AUTHORIZATION_CODE);
    req.setMethod("POST");
    req.setPathInfo("/access_token");

    try {
        oauthServlet.service(req, res);
        Assert.assertEquals("must return status OK", 200, res.getStatus());

        String tokenJson = res.getContentAsString();
        final JsonObject token = new JsonParser().parse(tokenJson).getAsJsonObject();

        Assert.assertTrue("response must be a valid json and have" + ACCESS_TOKEN + " field",
                token.has(ACCESS_TOKEN) && token.get(ACCESS_TOKEN).getAsString().length() > 0);

        Assert.assertTrue("response must be a valid json and have " + TOKEN_TYPE + " field",
                token.has(TOKEN_TYPE) && token.get(TOKEN_TYPE).getAsString().length() > 0);

        String accessToken = token.get(ACCESS_TOKEN).getAsString();
        String tokenType = token.get(TOKEN_TYPE).getAsString() + "fenixedu";

        Response result = target("bennu-oauth").path("test").path("test-scope").request()
                .header(HttpHeaders.AUTHORIZATION, tokenType + " " + accessToken).get(Response.class);

        Assert.assertEquals("request must fail", 401, result.getStatus());

    } catch (ServletException | IOException e) {
        Assert.fail(e.getMessage());
    }
}