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

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

Introduction

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

Prototype

public static boolean isBase64(final byte[] arrayOctet) 

Source Link

Document

Tests a given byte array to see if it contains only valid characters within the Base64 alphabet.

Usage

From source file:org.dd4t.databind.DD4TModelConverter.java

private static String decodeAndDecompressContent(String content) throws IOException {
    byte[] decoded;
    if (Base64.isBase64(content)) {
        System.out.println(">> length before base64 decode: " + content.getBytes("UTF-8").length);

        decoded = Base64.decodeBase64(content);
        System.out.println(">> length after base64 decode: " + decoded.length);
    } else {/*from w  w  w. j  a va2 s.  c o m*/
        decoded = content.getBytes();
    }

    String r = decompress(decoded);

    System.out.println(">> length after decompress: " + r.getBytes("UTF-8").length);
    System.out.println("Content is: " + r);
    return r;
}

From source file:org.dynamicloud.wiztorage.processor.StorageProcessorImpl.java

/**
 * This method uploads a file//from   ww w. j  ava 2 s.  c  om
 *
 * @param file        to be uploaded
 * @param description optional description
 * @param callback    will be called for the uploaded file
 * @throws org.dynamicloud.wiztorage.exception.StorageProcessorException if an error occurs
 */
@Override
public void uploadFile(final File file, final String description, UploadCallback callback)
        throws StorageProcessorException {
    try {
        StorageValidator validator = StorageValidator.StorageValidatorBuilder.getInstance(this.credentials);
        if (validator.existsFileName(file.getName())) {
            throw new StorageProcessorException(
                    "Filename already exists in Dynamicloud servers.  Probably this filename has an invalid state, try to execute cleanUp.");
        }
    } catch (RuntimeWiztorageException e) {
        throw new StorageProcessorException(e.getMessage());
    }

    final DynamicProvider<UploadBean> provider = new DynamicProviderImpl<UploadBean>(
            StorageProcessorImpl.this.credentials);
    final StringBuilder checkSums = new StringBuilder("");
    try {
        FileReader.FileReaderBuilder.getInstance().readFile(file, new FileReaderCallback() {
            @Override
            public void newChunk(String encode64Chunk, int index) {
                /**
                 * This API provides a SPI to implement your owm FileReader
                 * This validation guarantees that your implementations of FileReader always send a
                 * compatible Base64 String
                 */
                if (!Base64.isBase64(encode64Chunk)) {
                    throw new RuntimeWiztorageException("Invalid base64 encode.");
                }

                String cs = WiztorageUtils.generateCheckSum(encode64Chunk);

                UploadBean bean = new UploadBean();
                bean.setCheckSum(cs);
                bean.setChecked(0);
                bean.setSequence(index);
                bean.setSize(file.length());
                bean.setName(file.getName());
                bean.setDescription(description == null ? "" : description);
                bean.setType(WiztorageUtils.getType(file));
                bean.setChunk(encode64Chunk);

                try {
                    provider.saveRecord(
                            new RecordModel(StorageProcessorImpl.this.credentials.getModelIdentifier()), bean);
                } catch (Exception e) {
                    throw new RuntimeWiztorageException(e.getMessage());
                }

                checkSums.append(cs);
            }
        });

        /**
         * "Commit"
         */
        Query<UploadBean> query = provider.createQuery(new RecordModel(this.credentials.getModelIdentifier()));
        query.add(Conditions.equals("name", file.getName()));

        UploadBean bean = new UploadBean();
        bean.setChecked(1);

        provider.setBoundInstance(bean);
        provider.update(query);
        /**
         * End "Commit"
         */

        UploadInfo info = new UploadInfo();
        info.setSize(file.length());
        info.setName(file.getName());
        info.setDescription(description == null ? "" : description);
        info.setType(WiztorageUtils.getType(file));
        info.setUploadedFile(file);
        info.setCheckSum(WiztorageUtils.generateCheckSum(checkSums.toString()));

        callback.finishWork(info);
    } catch (Exception e) {
        /**
         * "Rollback"
         */
        try {
            DynamicProvider rollbackProvider = new DynamicProviderImpl(StorageProcessorImpl.this.credentials);
            Query query = rollbackProvider.createQuery(new RecordModel(this.credentials.getModelIdentifier()));
            query.add(Conditions.equals("name", file.getName()));

            rollbackProvider.delete(query);
        } catch (Exception ex) {
            throw new StorageProcessorException(ex.getMessage());
        }

        throw new StorageProcessorException(e.getMessage());
    }
}

From source file:org.dynamicloud.wiztorage.writer.FileWriterImpl.java

/**
 * This method writes an encode64Chunk into the destination.
 *
 * @param encode64Chunk to write into the file
 *///ww  w .  j  a  va2  s .  co m
@Override
public void writeFile(String encode64Chunk) throws FileWriterException {
    try {
        if (Base64.isBase64(encode64Chunk)) {
            byte[] bytes = Base64.decodeBase64(encode64Chunk.getBytes("UTF-8"));
            outputStream.write(bytes, 0, bytes.length);
        } else {
            throw new FileWriterException("Invalid base64 encode.");
        }
    } catch (UnsupportedEncodingException e) {
        throw new FileWriterException(e.getMessage());
    } catch (IOException e) {
        throw new FileWriterException(e.getMessage());
    }
}

From source file:org.flowable.app.filter.FlowableCookieFilter.java

protected String[] decodeCookie(String cookieValue) throws InvalidCookieException {
    for (int j = 0; j < cookieValue.length() % 4; j++) {
        cookieValue = cookieValue + "=";
    }/*from w ww  . j av  a 2 s.  co  m*/

    if (!Base64.isBase64(cookieValue.getBytes())) {
        throw new InvalidCookieException(
                "Cookie token was not Base64 encoded; value was '" + cookieValue + "'");
    }

    String cookieAsPlainText = new String(Base64.decodeBase64(cookieValue.getBytes()));

    String[] tokens = StringUtils.delimitedListToStringArray(cookieAsPlainText, DELIMITER);

    if ((tokens[0].equalsIgnoreCase("http") || tokens[0].equalsIgnoreCase("https"))
            && tokens[1].startsWith("//")) {
        // Assume we've accidentally split a URL (OpenID identifier)
        String[] newTokens = new String[tokens.length - 1];
        newTokens[0] = tokens[0] + ":" + tokens[1];
        System.arraycopy(tokens, 2, newTokens, 1, newTokens.length - 1);
        tokens = newTokens;
    }

    return tokens;
}

From source file:org.jasig.cas.services.web.beans.RegisteredServiceEditBean.java

/**
 * Configure username attribute provider.
 *
 * @param provider the provider//from ww  w .ja v  a2 s.c o  m
 * @param uBean the u bean
 */
private static void configureUsernameAttributeProvider(
        final RegisteredServiceUsernameAttributeProvider provider,
        final RegisteredServiceUsernameAttributeProviderEditBean uBean) {
    if (provider instanceof DefaultRegisteredServiceUsernameProvider) {
        uBean.setType(RegisteredServiceUsernameAttributeProviderEditBean.Types.DEFAULT.toString());
    } else if (provider instanceof AnonymousRegisteredServiceUsernameAttributeProvider) {
        final AnonymousRegisteredServiceUsernameAttributeProvider anonymous = (AnonymousRegisteredServiceUsernameAttributeProvider) provider;
        uBean.setType(RegisteredServiceUsernameAttributeProviderEditBean.Types.ANONYMOUS.toString());
        final PersistentIdGenerator generator = anonymous.getPersistentIdGenerator();
        if (generator instanceof ShibbolethCompatiblePersistentIdGenerator) {
            final ShibbolethCompatiblePersistentIdGenerator sh = (ShibbolethCompatiblePersistentIdGenerator) generator;

            String salt = new String(sh.getSalt(), Charset.defaultCharset());
            if (Base64.isBase64(salt)) {
                salt = new String(Base64.decodeBase64(salt));
            }

            uBean.setValue(salt);
        }
    } else if (provider instanceof PrincipalAttributeRegisteredServiceUsernameProvider) {
        final PrincipalAttributeRegisteredServiceUsernameProvider p = (PrincipalAttributeRegisteredServiceUsernameProvider) provider;
        uBean.setType(RegisteredServiceUsernameAttributeProviderEditBean.Types.ATTRIBUTE.toString());
        uBean.setValue(p.getUsernameAttribute());
    }
}

From source file:org.jbpm.designer.repository.VFSRepositoryGitFileSystemTest.java

private String decodeUniqueId(String uniqueId) {
    if (Base64.isBase64(uniqueId)) {
        byte[] decoded = Base64.decodeBase64(uniqueId);
        try {// w w w.j  av  a  2s. c  o  m
            String uri = new String(decoded, "UTF-8");

            return UriUtils.encode(uri);
        } catch (UnsupportedEncodingException e) {

        }
    }

    return UriUtils.encode(uniqueId);
}

From source file:org.jbpm.designer.web.preprocessing.impl.JbpmPreprocessingUnit.java

private void setupDefaultWorkitemConfigs(String location, Repository repository) {
    try {/*  w  w  w .j  a va2 s. c  o m*/
        location = UriUtils.encode(location);
        // push default configuration wid
        // check classpath first
        InputStream widIn = this.getClass().getClassLoader().getResourceAsStream(defaultClasspathWid);
        String createdUUID;
        if (widIn != null) {
            createdUUID = createAssetIfNotExisting(repository, location, "WorkDefinitions", "wid",
                    IOUtils.toByteArray(widIn));
        } else {
            ST widConfigTemplate = new ST(readFile(default_widconfigtemplate), '$', '$');
            createdUUID = createAssetIfNotExisting(repository, location, "WorkDefinitions", "wid",
                    widConfigTemplate.render().getBytes("UTF-8"));

        }
        if (Base64.isBase64(createdUUID)) {
            byte[] decoded = Base64.decodeBase64(createdUUID);
            try {
                createdUUID = new String(decoded, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        if (vfsService != null && createdUUID != null) {
            Path newWidAssetPath = vfsService.get(UriUtils.encode(createdUUID));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.jbpm.designer.web.server.CalledElementServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String profileName = Utils.getDefaultProfileName(req.getParameter("profile"));
    String processPackage = req.getParameter("ppackage");
    String processId = req.getParameter("pid");
    String action = req.getParameter("action");

    if (profile == null) {
        profile = _profileService.findProfile(req, profileName);
    }/*from   w ww .  j  a  va  2 s  .c  o  m*/
    if (action != null && action.equals("openprocessintab")) {
        String retValue = "";
        List<String> allPackageNames = ServletUtil.getPackageNamesFromRepository(profile);
        if (allPackageNames != null && allPackageNames.size() > 0) {
            for (String packageName : allPackageNames) {
                List<String> allProcessesInPackage = ServletUtil.getAllProcessesInPackage(packageName, profile);
                if (allProcessesInPackage != null && allProcessesInPackage.size() > 0) {
                    for (String p : allProcessesInPackage) {
                        Asset<String> processContent = ServletUtil.getProcessSourceContent(p, profile);
                        Pattern idPattern = Pattern.compile("<\\S*process[^\"]+id=\"([^\"]+)\"",
                                Pattern.MULTILINE);
                        Matcher idMatcher = idPattern.matcher(processContent.getAssetContent());
                        if (idMatcher.find()) {
                            String pid = idMatcher.group(1);
                            String pidcontent = ServletUtil.getProcessImageContent(packageName, pid, profile);
                            if (pid != null && pid.equals(processId)) {
                                String uniqueId = processContent.getUniqueId();
                                if (Base64.isBase64(uniqueId)) {
                                    byte[] decoded = Base64.decodeBase64(uniqueId);
                                    try {
                                        uniqueId = new String(decoded, "UTF-8");
                                    } catch (UnsupportedEncodingException e) {
                                        e.printStackTrace();
                                    }
                                }
                                retValue = processContent.getName() + "." + processContent.getAssetType() + "|"
                                        + uniqueId;
                                break;
                            }
                        }
                    }
                }
            }
        }
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/plain");
        resp.getWriter().write(retValue);
    } else if (action != null && action.equals("showruleflowgroups")) {
        //Query for RuleFlowGroups
        final List<RefactoringPageRow> results = queryService.query("FindRuleFlowNamesQuery",
                new HashSet<ValueIndexTerm>() {
                    {
                        add(new ValueRuleAttributeIndexTerm("ruleflow-group"));
                        add(new ValueRuleAttributeValueIndexTerm("*"));
                    }
                }, true);

        final List<String> ruleFlowGroupNames = new ArrayList<String>();
        for (RefactoringPageRow row : results) {
            ruleFlowGroupNames.add((String) row.getValue());
        }
        Collections.sort(ruleFlowGroupNames);

        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json");
        resp.getWriter().write(getRuleFlowGroupsInfoAsJSON(ruleFlowGroupNames).toString());

    } else if (action != null && action.equals("showdatatypes")) {
        final List<RefactoringPageRow> results2 = queryService.query("DesignerFindTypesQuery",
                new HashSet<ValueIndexTerm>() {
                    {
                        add(new ValueTypeIndexTerm("*"));
                    }
                }, true);
        final List<String> dataTypeNames = new ArrayList<String>();
        for (RefactoringPageRow row : results2) {
            dataTypeNames.add((String) row.getValue());
        }
        Collections.sort(dataTypeNames);
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json");
        resp.getWriter().write(getDataTypesInfoAsJSON(dataTypeNames).toString());
    } else {
        String retValue = "false";
        List<String> allPackageNames = ServletUtil.getPackageNamesFromRepository(profile);
        Map<String, String> processInfo = new HashMap<String, String>();
        if (allPackageNames != null && allPackageNames.size() > 0) {
            for (String packageName : allPackageNames) {
                List<String> allProcessesInPackage = ServletUtil.getAllProcessesInPackage(packageName, profile);
                if (allProcessesInPackage != null && allProcessesInPackage.size() > 0) {
                    for (String p : allProcessesInPackage) {
                        Asset<String> processContent = ServletUtil.getProcessSourceContent(p, profile);
                        Pattern idPattern = Pattern.compile("<\\S*process[^\"]+id=\"([^\"]+)\"",
                                Pattern.MULTILINE);
                        Matcher idMatcher = idPattern.matcher(processContent.getAssetContent());
                        if (idMatcher.find()) {
                            String pid = idMatcher.group(1);
                            String pidcontent = ServletUtil
                                    .getProcessImageContent(processContent.getAssetLocation(), pid, profile);
                            if (pid != null && !(packageName.equals(processPackage) && pid.equals(processId))) {
                                processInfo.put(pid + "|" + processContent.getAssetLocation(),
                                        pidcontent != null ? pidcontent : "");
                            }
                        }
                    }

                }
            }
        }
        retValue = getProcessInfoAsJSON(processInfo).toString();
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json");
        resp.getWriter().write(retValue);
    }
}

From source file:org.jbpm.designer.web.server.TaskFormsEditorServlet.java

private JSONObject storeTaskFormInRepository(String formType, String taskName, String packageName,
        String formValue, Repository repository) throws Exception {

    repository.deleteAssetFromPath(packageName + "/" + taskName + TASKFORM_NAME_EXTENSION + "." + formType);

    AssetBuilder builder = AssetBuilderFactory.getAssetBuilder(Asset.AssetType.Byte);
    builder.location(packageName).name(taskName + TASKFORM_NAME_EXTENSION).type(formType)
            .content(formValue.getBytes("UTF-8"));

    repository.createAsset(builder.getAsset());

    Asset newFormAsset = repository//from ww w .j  a v a2 s . c o  m
            .loadAssetFromPath(packageName + "/" + taskName + TASKFORM_NAME_EXTENSION + "." + formType);

    String uniqueId = newFormAsset.getUniqueId();
    if (Base64.isBase64(uniqueId)) {
        byte[] decoded = Base64.decodeBase64(uniqueId);
        try {
            uniqueId = new String(decoded, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    JSONObject retObj = new JSONObject();
    retObj.put("formid", uniqueId);

    return retObj;
}

From source file:org.jbpm.designer.web.server.TaskFormsEditorServlet.java

private String getTaskFormFromRepository(String formType, String taskName, String packageName,
        Repository repository) {/*ww  w  .j  av  a 2  s.c om*/
    try {
        Asset<String> formAsset = repository
                .loadAssetFromPath(packageName + "/" + taskName + TASKFORM_NAME_EXTENSION + "." + formType);

        if (formType.equals(FORMMODELER_FILE_EXTENSION)) {
            String uniqueId = formAsset.getUniqueId();
            if (Base64.isBase64(uniqueId)) {
                byte[] decoded = Base64.decodeBase64(uniqueId);
                try {
                    uniqueId = new String(decoded, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            return formAsset.getName() + "." + formAsset.getAssetType() + "|" + uniqueId;
        } else {
            return formAsset.getAssetContent();
        }
    } catch (NoSuchFileException anfe) {
        try {
            String formValue = "";
            if (formType.equals(FORMMODELER_FILE_EXTENSION)) {
                formValue = formModelerService
                        .buildEmptyFormXML(taskName + TASKFORM_NAME_EXTENSION + "." + formType);
            }

            AssetBuilder builder = AssetBuilderFactory.getAssetBuilder(Asset.AssetType.Byte);
            builder.location(packageName).name(taskName + TASKFORM_NAME_EXTENSION).type(formType)
                    .content(formValue.getBytes("UTF-8"));
            repository.createAsset(builder.getAsset());

            Asset<String> newFormAsset = repository
                    .loadAssetFromPath(packageName + "/" + taskName + TASKFORM_NAME_EXTENSION + "." + formType);

            String uniqueId = newFormAsset.getUniqueId();
            if (Base64.isBase64(uniqueId)) {
                byte[] decoded = Base64.decodeBase64(uniqueId);
                try {
                    uniqueId = new String(decoded, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }

            if (formType.equals(FORMMODELER_FILE_EXTENSION)) {
                return newFormAsset.getName() + "." + newFormAsset.getAssetType() + "|" + uniqueId;
            } else {
                return formValue;
            }
        } catch (Exception e) {
            e.printStackTrace();
            _logger.error(e.getMessage());
        }
    }
    return "false";
}