Example usage for org.apache.commons.codec.binary Base64 Base64

List of usage examples for org.apache.commons.codec.binary Base64 Base64

Introduction

In this page you can find the example usage for org.apache.commons.codec.binary Base64 Base64.

Prototype

public Base64() 

Source Link

Document

Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.

Usage

From source file:adams.flow.transformer.DownloadContent.java

/**
 * Executes the flow item./*from  ww  w  . j  a v  a 2 s .  c  o  m*/
 *
 * @return      null if everything is fine, otherwise error message
 */
@Override
@MixedCopyright(author = "http://stackoverflow.com/users/2920131/lboix", license = License.CC_BY_SA_3, url = "http://stackoverflow.com/a/13122190", note = "handling basic authentication")
protected String doExecute() {
    String result;
    URL url;
    BufferedInputStream input;
    byte[] buffer;
    byte[] bufferSmall;
    int len;
    StringBuilder content;
    URLConnection conn;
    String basicAuth;

    input = null;
    content = new StringBuilder();
    try {
        if (m_InputToken.getPayload() instanceof String)
            url = new URL((String) m_InputToken.getPayload());
        else if (m_InputToken.getPayload() instanceof BaseURL)
            url = ((BaseURL) m_InputToken.getPayload()).urlValue();
        else
            url = (URL) m_InputToken.getPayload();

        conn = url.openConnection();
        if (url.getUserInfo() != null) {
            basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
            conn.setRequestProperty("Authorization", basicAuth);
        }
        input = new BufferedInputStream(conn.getInputStream());
        buffer = new byte[m_BufferSize];
        while ((len = input.read(buffer)) > 0) {
            if (len < m_BufferSize) {
                bufferSmall = new byte[len];
                System.arraycopy(buffer, 0, bufferSmall, 0, len);
                content.append(new String(bufferSmall));
            } else {
                content.append(new String(buffer));
            }
        }

        m_OutputToken = new Token(content.toString());
        content = null;
        result = null;
    } catch (Exception e) {
        result = handleException("Problem downloading '" + m_InputToken.getPayload() + "': ", e);
    } finally {
        try {
            if (input != null)
                input.close();
        } catch (Exception e) {
            // ignored
        }
    }

    return result;
}

From source file:com.wavemaker.tools.util.TomcatServer.java

private HttpURLConnection prepareConnection(HttpURLConnection con) {

    // Copied from Catalina's DeployTask
    con.setRequestProperty("User-Agent", "Catalina-Ant-Task/1.0");

    String input = this.username + ":" + this.password;
    String output = new String(new Base64().encode(input.getBytes())).trim();
    con.setRequestProperty("Authorization", "Basic " + output);

    try {/* www .  j  av a  2  s.co m*/
        con.connect();
    } catch (IOException ex) {
        throw new ConfigurationException(ex);
    }
    return con;
}

From source file:com.jivesoftware.authHelper.customescheme.negotiate.CustomNegotiateScheme.java

/**
 * Processes the Negotiate challenge./*  ww w.  j  a v  a 2s.c  o m*/
 *
 * @param challenge the challenge string
 *
 * @since 3.0
 */
public void processChallenge(final String challenge) {
    //System.out.println("%%%%in process challenge%%% challenge="+challenge);
    LOG.info("enter processChallenge(challenge=\"" + challenge + "\")");
    if (challenge.startsWith("Negotiate")) {
        if (!isComplete()) {
            if (retryCount++ > MAX_RETRY_COUNT) {
                state = FAILED;
                LOG.info("*** Failed to negotiate authentication after " + MAX_RETRY_COUNT
                        + " retries. Giving up. ***");
            } else {
                state = NEGOTIATING;
            }
        }

        if (challenge.startsWith("Negotiate ")) {
            token = new Base64().decode(challenge.substring(10).getBytes());
        }

    } else {
        token = new byte[0];
    }
}

From source file:eu.aniketos.ncvm.impl.Tests.java

/**
 * Perform various tests to ensure the PVM is accessible and acts as expected.
 * @param pvm the service to test.//ww  w .j a  v  a 2  s. c  o m
 * @param conspec a ConSpec security policy to send to the service.
 * @param details info about the service to be checked. For example, the name of the service in the marketplace.
 * @return true if the service was accessible and the tests returned the results expected.
 */
static boolean testPVM(PropertyVerificationService pvm, String conspec, String details) {
    int passed = 0;
    boolean result = false;

    if (pvm != null) {
        Activator.logLine("Calling PVM.");

        Base64 encoder = new Base64();
        String agreementTemplateEncoded = "";
        //agreementTemplateEncoded = encodeData(agreementTemplate);

        PropertyVerificationResult verificationProperty;

        agreementTemplateEncoded = encoder.encodeToString(conspec.getBytes());

        Activator.logLine("Checking WSDL at: " + details);

        verificationProperty = pvm.verifyTechnicalTrustProperties(agreementTemplateEncoded, details);
        Activator.logLine("PVM result: " + verificationProperty.getVerificationResult() + "; "
                + verificationProperty.getVerificationExplaination());

        if (verificationProperty.getVerificationResult() >= 0) {
            passed++;
        }
    } else {
        Activator.logLine("PVM not found");
    }

    if (passed == 1) {
        Activator.logLine("PVM tests passed");
        result = true;
    } else {
        Activator.logLine("PVM tests failed");
        result = false;
    }

    return result;
}

From source file:adams.flow.sink.DownloadFile.java

/**
 * Executes the flow item./*from  ww  w. j  a  v a2 s.  co m*/
 *
 * @return      null if everything is fine, otherwise error message
 */
@Override
@MixedCopyright(author = "http://stackoverflow.com/users/2920131/lboix", license = License.CC_BY_SA_3, url = "http://stackoverflow.com/a/13122190", note = "handling basic authentication")
protected String doExecute() {
    String result;
    URL url;
    BufferedInputStream input;
    BufferedOutputStream output;
    FileOutputStream fos;
    byte[] buffer;
    int len;
    int count;
    URLConnection conn;
    String basicAuth;

    input = null;
    output = null;
    fos = null;
    try {
        if (m_InputToken.getPayload() instanceof String)
            url = new URL((String) m_InputToken.getPayload());
        else
            url = (URL) m_InputToken.getPayload();

        conn = url.openConnection();
        if (url.getUserInfo() != null) {
            basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
            conn.setRequestProperty("Authorization", basicAuth);
        }
        input = new BufferedInputStream(conn.getInputStream());
        fos = new FileOutputStream(m_OutputFile.getAbsoluteFile());
        output = new BufferedOutputStream(fos);
        buffer = new byte[m_BufferSize];
        count = 0;
        while ((len = input.read(buffer)) > 0) {
            count++;
            output.write(buffer, 0, len);
            if (count % 100 == 0)
                output.flush();
        }
        output.flush();

        result = null;
    } catch (Exception e) {
        result = handleException("Problem downloading '" + m_InputToken.getPayload() + "': ", e);
    } finally {
        FileUtils.closeQuietly(input);
        FileUtils.closeQuietly(output);
        FileUtils.closeQuietly(fos);
    }

    return result;
}

From source file:com.titilink.camel.rest.util.OtherUtil.java

/**
 * ?MD5????BASE64?//from   ww  w  . j av  a2s  .c  o  m
 *
 * @param str --??
 * @return --??
 */
public static String md5AndBase64Encode(String str) {
    byte[] b = md5(str);
    if (b == null) {
        throw new RuntimeException("md5 encode err!");
    }
    Base64 b64 = new Base64();
    b = b64.encode(b);
    return new String(b);
}

From source file:mx.bigdata.sat.cfdi.CFDv33.java

@Override
public void verificar() throws Exception {
    String certStr = document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);

    X509Certificate cert = KeyLoaderFactory
            .createInstance(KeyLoaderEnumeration.PUBLIC_KEY_LOADER, new ByteArrayInputStream(cbs)).getKey();

    String sigStr = document.getSello();
    byte[] signature = b64.decode(sigStr);
    byte[] bytes = getOriginalBytes();
    Signature sig = Signature.getInstance("SHA256withRSA");
    sig.initVerify(cert);//from www. j  a v a2s. com
    sig.update(bytes);
    boolean bool = sig.verify(signature);
    if (!bool) {
        throw new Exception("Invalid signature");
    }
}

From source file:license.ExtraTestWakeLicense.java

/**
 * ?//  w  w  w.j ava2 s .  c o m
 * ;blowfish??
 * ;md5--rsa--base64??
 * 
 */
public String toString(ProjectInfo pi) {
    System.out.println("?");

    try {
        return encryptProjectInfo(pi) + "\n" + new Base64().encodeAsString(rsa());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.microsoft.azure.oidc.token.impl.SimpeTokenParser.java

private String decodePart(final String part) {
    if (part == null) {
        throw new PreconditionException("Required parameter is null");
    }/*from   ww  w  .j  a  va 2  s . com*/
    try {
        final Base64 decoder = new Base64();
        return new String(decoder.decode(part), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new GeneralException("Unsupported Encoding Exception", e);
    }
}

From source file:UploadTest.java

@Test
public void test_upload_data() {
    try {/*from  w w w . j a  va 2 s .com*/

        try {
            url = new URL("https://api.localhost/resource/frl:6376979/data");
            httpCon = (HttpsURLConnection) url.openConnection();
            String userpass = user + ":" + password;
            basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
            httpCon.setRequestProperty("Authorization", basicAuth);
        } catch (Exception e) {
            e.printStackTrace();
        }

        List<String> response = new ArrayList<String>();
        httpCon.setRequestProperty("Content-Type", "application/json");
        httpCon.setRequestProperty("Accept", "application/json");
        httpCon.setDoOutput(true);
        httpCon.setRequestMethod("PUT");
        httpCon.setReadTimeout(5000);
        String content = "{\"contentType\":\"monograph\",\"accessScheme\":\"public\",\"publishScheme\":\"public\"}";
        try (OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream())) {
            out.write(content);
        }
        System.out.println("HELLO");
        // System.out.println(httpCon.getResponseCode());

        httpCon.getInputStream();
        System.out.println("HELLO");
        int status = httpCon.getResponseCode();
        System.out.println("HELLO");
        if (status == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                response.add(line);
            }
            reader.close();
            httpCon.disconnect();
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }

        // httpCon.disconnect();
        System.out.println("Status: " + status + "\nResponse: " + response.toString());

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}