Example usage for com.liferay.portal.kernel.util Base64 encode

List of usage examples for com.liferay.portal.kernel.util Base64 encode

Introduction

In this page you can find the example usage for com.liferay.portal.kernel.util Base64 encode.

Prototype

public static String encode(byte[] raw) 

Source Link

Usage

From source file:by.belisa.util.OnlineConvert.java

License:MIT License

/**
 *
 * convert Make a API call to convert file/url/hash based on parameters and
 * return xml response./*from  w  ww.  j ava  2 s  .c  om*/
 *
 * @param targetTypeMethod To which file you want to convert (like convert-to-jpg,
 * convert-to-mp3)
 * @param sourceType The source types you can set (URL, FILE_PATH and
 * FILE_BASE64)
 * @param source Source can be provide based on sourceType if sourceType =
 * URL you have to provide url string to this param.
 * @param sourceName Provide file Name. This param used only with
 * sourceType= FILE_PATH or FILE_BASE64
 * @param formatOptions Provide file conversion required extra parameters as
 * array using this param.
 * @param notificationUrl For set notification url for api actions.
 * @return xml response string from server.
 * @throws java.lang.Exception when required values of variables not found
 * in an Instance of class or in the arguments
 */
public String convert(String targetTypeMethod, String sourceType, String source, String sourceName,
        Map<String, String> formatOptions, String notificationUrl) throws Exception {
    if (null == this.targetTypeOptions.get(targetTypeMethod)) {
        throw new Exception("Invalid Target Type.");
    }

    this.targetType = this.targetTypeOptions.get(targetTypeMethod);

    if (null == this.sourceTypeOptions.get(sourceType)) {
        throw new Exception("Invalid Source Type.");
    }

    this.sourceType = sourceType;

    if (SOURCE_TYPE_FILE_BASE64.equals(this.sourceType) || SOURCE_TYPE_FILE_PATH.equals(this.sourceType)) {
        if (source == null || source.length() < 1) {
            throw new Exception("Invalid Source Name.");
        }
    }

    if (this.sourceType.equals(SOURCE_TYPE_FILE_PATH)) {
        if (!new File(source).exists()) {
            throw new Exception("File not found: " + source);
        }
        Path path = Paths.get(source);
        source = new String(Base64.encode(Files.readAllBytes(path)));
        //source = Base64.encodeBase64String(Files.readAllBytes(path));
    }

    Map<String, String> data = new HashMap<String, String>();
    data.put("apiKey", this.apiKey);
    data.put("targetType", this.targetTypeOptions.get(targetTypeMethod));
    data.put("targetMethod", targetTypeMethod);
    data.put("testMode", (String.valueOf(this.testMode)));
    data.put("notificationUrl", notificationUrl);

    String formatOptionsXml = "";
    if (null != formatOptions) {
        formatOptionsXml = this.getFormatMap2XML(formatOptions);
    }

    String apiCallResponse;
    List response;

    if (this.sourceType.equals(OnlineConvert.SOURCE_TYPE_URL)) {
        data.put("sourceUrl", source);
        apiCallResponse = this.apiCall("queue-insert", data, formatOptionsXml);
    } else {
        List<Map> query = new ArrayList<Map>();
        Map<String, String> file = new HashMap<String, String>();
        file.put("fileName", sourceName);
        file.put("fileData", source);
        query.add(OnlineConvert.QUEUE_COMMAN_PARAMS, data);
        query.add(OnlineConvert.QUEUE_FILE_METADATA_PARAMS, file);
        apiCallResponse = this.apiCall("queue-insert", query, formatOptionsXml);
    }

    response = this.getXML2Map(apiCallResponse);
    if (!response.isEmpty()) {
        Map responseStatus = (HashMap) response.get(OnlineConvert.QUEUE_ANSWER_STATUS);
        Map responseParams = (HashMap) response.get(OnlineConvert.QUEUE_ANSWER_PARAMS);
        if (Integer.parseInt(responseStatus.get("code").toString()) == 0) {
            this.hash = (String) responseParams.get("hash");
            this.downloadUrl = (String) responseParams.get("downloadUrl");
        }
    }

    this.url = OnlineConvert.URL;
    return apiCallResponse;
}

From source file:com.ihg.me2.service.impl.EmailAttachmentServiceImpl.java

License:Open Source License

public String getEmailAttachmentFileById(long emailAttachmentId) throws PortalException, SystemException {
    EmailAttachment emailAttachment = EmailAttachmentLocalServiceUtil.getEmailAttachment(emailAttachmentId);
    Blob blob = emailAttachment.getAttachmentFileText();
    String attachmentFileText = null;

    try {/*  w  ww  . j av a  2  s  . c om*/
        byte[] blobBytes = blob.getBytes(1, (int) blob.length());
        attachmentFileText = new String(blobBytes);

        System.out.println(attachmentFileText);
        for (byte data : blobBytes) {
            System.out.print(data + ",");
        }
        FileOutputStream outputStream = new FileOutputStream("c:/test/sign.jpg");
        outputStream.write(blobBytes);
        outputStream.close();
        blob.free();

        return Base64.encode(blobBytes);

        //return blobBytes;
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:com.liferay.ci.http.BaseConnectImpl.java

License:Open Source License

protected InputStream connect(AuthConnectionParams authParams, String urlSuffix, boolean appendUrlPrefix)
        throws IOException {

    if (authParams != null) {
        _connectionParams = authParams;// ww w.  j  a  v a2 s  . com
    }

    String user = _connectionParams.getUser();
    String password = _connectionParams.getPassword();

    String connectionURL = "";

    if (appendUrlPrefix) {
        connectionURL += authParams.getBaseApiUrl();
    }

    connectionURL += urlSuffix;

    URL url = new URL(connectionURL);

    URLConnection uc = url.openConnection();

    String userpass = user + " : " + new String(Base64.decode(password));

    String encodedUserPass = new String(Base64.encode(userpass.getBytes()));

    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            String decodedPassword = new String(Base64.decode(_connectionParams.getPassword()));

            return new PasswordAuthentication(_connectionParams.getUser(), decodedPassword.toCharArray());
        }
    });

    String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(encodedUserPass.getBytes());

    uc.setRequestProperty("Authorization", basicAuth);

    return uc.getInputStream();
}

From source file:com.liferay.ci.jenkins.action.ConfigurationActionImpl.java

License:Open Source License

@Override
public void processAction(PortletConfig portletConfig, ActionRequest actionRequest,
        ActionResponse actionResponse) throws Exception {

    String baseAPIURL = getParameter(actionRequest, "baseapiurl");

    if (Validator.isNull(baseAPIURL)) {
        SessionErrors.add(actionRequest, "baseApiURLError");
    }/* www.  ja  v a2 s  . com*/

    String user = getParameter(actionRequest, "username");
    String password = getParameter(actionRequest, "password");

    if (Validator.isNull(user) || Validator.isNull(password)) {
        SessionErrors.add(actionRequest, "httpAuthError");
    }

    super.processAction(portletConfig, actionRequest, actionResponse);

    String base64EncodedPassword = Base64.encode(password.getBytes());

    PortletPreferences preferences = actionRequest.getPreferences();

    preferences.setValue("password", base64EncodedPassword);

    preferences.store();
}

From source file:com.liferay.mail.util.PasswordUtil.java

License:Open Source License

public static String encrypt(String unencryptedPassword) {
    String encryptedPassword = null;

    try {//from  w w w.  j  av a 2  s  . co  m
        byte[] bytes = unencryptedPassword.getBytes(StringPool.UTF8);

        encryptedPassword = Base64.encode(bytes);
    } catch (UnsupportedEncodingException uee) {
        _log.error("Unable to encrypt the password", uee);
    }

    return encryptedPassword;
}

From source file:com.liferay.petra.encryptor.Encryptor.java

License:Open Source License

public static String encrypt(Key key, String plainText) throws EncryptorException {

    if (key == null) {
        if (_log.isWarnEnabled()) {
            _log.warn("Skip encrypting based on a null key");
        }//ww  w  .  java  2s.  c om

        return plainText;
    }

    byte[] encryptedBytes = encryptUnencoded(key, plainText);

    return Base64.encode(encryptedBytes);
}

From source file:com.liferay.petra.encryptor.Encryptor.java

License:Open Source License

public static String serializeKey(Key key) {
    return Base64.encode(key.getEncoded());
}

From source file:com.liferay.portlet.amazonrankings.util.AmazonSignedRequestsUtil.java

License:Open Source License

private static String _generateSignature(String data) throws Exception {
    String amazonSecretAccessKey = AmazonRankingsUtil.getAmazonSecretAccessKey();

    SecretKeySpec secretKeySpec = new SecretKeySpec(amazonSecretAccessKey.getBytes(), _HMAC_SHA256_ALGORITHM);

    Mac mac = Mac.getInstance(_HMAC_SHA256_ALGORITHM);

    mac.init(secretKeySpec);//from  w w  w .ja va2s  . com

    byte[] bytes = mac.doFinal(data.getBytes());

    String signature = Base64.encode(bytes);

    return StringUtil.replace(signature, new String[] { StringPool.EQUALS, StringPool.PLUS },
            new String[] { "%3D", "%2B" });
}

From source file:com.liferay.util.Encryptor.java

License:Open Source License

public static String encrypt(Key key, String plainText) throws EncryptorException {

    byte[] encryptedBytes = encryptUnencoded(key, plainText);

    return Base64.encode(encryptedBytes);
}

From source file:com.liferay.wsrp.consumer.portlet.ConsumerPortlet.java

License:Open Source License

protected void processUpdateResponse(PortletRequest portletRequest, StateAwareResponse stateAwareResponse,
        WSRPConsumerManager wsrpConsumerManager, ServiceHolder serviceHolder, UpdateResponse updateResponse)
        throws Exception {

    PortletSession portletSession = portletRequest.getPortletSession();

    if (updateResponse == null) {
        return;// w  w  w. j  a  v  a2s  .  c  o  m
    }

    portletSession.setAttribute(WebKeys.MARKUP_CONTEXT, updateResponse.getMarkupContext());

    NavigationalContext navigationalContext = updateResponse.getNavigationalContext();

    if (navigationalContext != null) {
        String opaqueValue = navigationalContext.getOpaqueValue();

        if (Validator.isNotNull(opaqueValue)) {
            byte[] opaqueValueBytes = opaqueValue.getBytes(StringPool.UTF8);

            opaqueValue = Base64.toURLSafe(Base64.encode(opaqueValueBytes));

            stateAwareResponse.setRenderParameter("wsrp-navigationalState", opaqueValue);
        }

        NamedString[] publicValues = navigationalContext.getPublicValues();

        if (publicValues != null) {
            for (NamedString publicValue : publicValues) {
                String name = publicValue.getName();
                String value = publicValue.getValue();

                if (Validator.isNotNull(value)) {
                    stateAwareResponse.setRenderParameter(name, value);
                } else {
                    stateAwareResponse.removePublicRenderParameter(name);
                }
            }
        }
    }

    PortletContext portletContext = updateResponse.getPortletContext();

    if (portletContext != null) {
        portletSession.setAttribute(WebKeys.PORTLET_CONTEXT, portletContext);
    }

    SessionContext sessionContext = updateResponse.getSessionContext();

    updateSessionContext(portletSession, serviceHolder, sessionContext);

    String portletMode = updateResponse.getNewMode();

    if (Validator.isNotNull(portletMode)) {
        stateAwareResponse.setPortletMode(getPortletMode(portletMode));
    }

    String windowState = updateResponse.getNewWindowState();

    if (Validator.isNotNull(windowState)) {
        stateAwareResponse.setWindowState(getWindowState(windowState));
    }

    Event[] events = updateResponse.getEvents();

    if (events != null) {
        for (Event event : events) {
            QName qName = wsrpConsumerManager.getEventQName(event.getName());

            event.setName(qName);

            stateAwareResponse.setEvent(qName, event);
        }
    }
}