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.jbpm.designer.web.server.TaskFormsServlet.java

public JSONObject storeTaskForm(TaskFormInfo taskForm, String location, Repository repository)
        throws Exception {
    try {//  w w  w  . ja va2  s.c  o  m
        JSONObject retObj = new JSONObject();

        repository.deleteAssetFromPath(
                taskForm.getPkgName() + "/" + taskForm.getId() + "." + FORMTEMPLATE_FILE_EXTENSION);

        // create the form meta form asset
        AssetBuilder builder = AssetBuilderFactory.getAssetBuilder(Asset.AssetType.Byte);
        builder.name(taskForm.getId()).location(location).type(FORMTEMPLATE_FILE_EXTENSION)
                .content(taskForm.getMetaOutput().getBytes("UTF-8"));

        repository.createAsset(builder.getAsset());

        Asset newFormAsset = repository.loadAssetFromPath(
                taskForm.getPkgName() + "/" + taskForm.getId() + "." + FORMTEMPLATE_FILE_EXTENSION);

        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();
            }
        }
        retObj.put("ftluri", uniqueId);

        // create the modeler form asset
        repository.deleteAssetFromPath(
                taskForm.getPkgName() + "/" + taskForm.getId() + "." + FORMMODELER_FILE_EXTENSION);
        AssetBuilder modelerBuilder = AssetBuilderFactory.getAssetBuilder(Asset.AssetType.Byte);
        modelerBuilder.name(taskForm.getId()).location(location).type(FORMMODELER_FILE_EXTENSION)
                .content(taskForm.getModelerOutput().getBytes("UTF-8"));

        repository.createAsset(modelerBuilder.getAsset());

        Asset newModelerFormAsset = repository.loadAssetFromPath(
                taskForm.getPkgName() + "/" + taskForm.getId() + "." + FORMMODELER_FILE_EXTENSION);

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

        retObj.put("formuri", modelerUniqueId);

        return retObj;

    } catch (Exception e) {
        _logger.error(e.getMessage());
        return new JSONObject();
    }
}

From source file:org.maodian.flyingcat.xmpp.codec.SASLCodec.java

@Override
public Object decode(XMLStreamReader xmlsr) {
    String mechanism = xmlsr.getAttributeValue("", "mechanism");
    if (StringUtils.equals("PLAIN", mechanism)) {
        String base64Data = null;
        try {/*from w  ww .  j  av a 2 s .  co  m*/
            base64Data = xmlsr.getElementText();
        } catch (XMLStreamException e) {
            throw new RuntimeException(e);
        }

        if (!Base64.isBase64(base64Data)) {
            throw new XmppException(SASLError.INCORRECT_ENCODING);
        }

        byte[] value = Base64.decodeBase64(base64Data);
        String text = new String(value, StandardCharsets.UTF_8);

        // apply PLAIN SASL mechanism whose rfc locates at http://tools.ietf.org/html/rfc4616
        int[] nullPosition = { -1, -1 };
        int nullIndex = 0;
        for (int i = 0; i < text.length(); ++i) {
            if (text.codePointAt(i) == 0) {
                // a malicious base64 value may contain more than two null character
                if (nullIndex > 1) {
                    throw new XmppException(SASLError.MALFORMED_REQUEST);
                }
                nullPosition[nullIndex++] = i;
            }
        }

        if (nullPosition[0] == -1 || nullPosition[1] == -1) {
            throw new XmppException("The format is invalid", SASLError.MALFORMED_REQUEST);
        }
        String authzid = StringUtils.substring(text, 0, nullPosition[0]);
        String authcid = StringUtils.substring(text, nullPosition[0] + 1, nullPosition[1]);
        String password = StringUtils.substring(text, nullPosition[1] + 1);

        if (authzid.getBytes(StandardCharsets.UTF_8).length > 255
                || authcid.getBytes(StandardCharsets.UTF_8).length > 255
                || password.getBytes(StandardCharsets.UTF_8).length > 255) {
            throw new XmppException(
                    "authorization id, authentication id and password should be equal or less than 255 bytes",
                    SASLError.MALFORMED_REQUEST);
        }
        return new Auth(authzid, authcid, password);
    } else {
        throw new XmppException(SASLError.INVALID_MECHANISM).set("mechanism", mechanism);
    }
}

From source file:org.n52.wps.test.AllTestsIT.java

public static void checkInlineResultBase64(String response) {

    ExecuteResponseDocument document = null;

    try {/*from  w ww  .  j av  a  2 s.  c o  m*/
        document = ExecuteResponseDocument.Factory.parse(response);
    } catch (Exception e) {
        System.err.println("Could not parse execute response document.");
    }

    assertThat(document, not(nullValue()));

    ProcessOutputs outputs = document.getExecuteResponse().getProcessOutputs();

    assertThat(outputs, not(nullValue()));
    assertThat(outputs.sizeOfOutputArray(), not(0));

    OutputDataType outputDataType = document.getExecuteResponse().getProcessOutputs().getOutputArray(0);

    assertThat(outputDataType, not(nullValue()));

    DataType data = outputDataType.getData();

    assertTrue(data.isSetComplexData());

    ComplexDataType complexData = outputDataType.getData().getComplexData();

    assertThat(complexData, not(nullValue()));

    Node domNode = complexData.getDomNode();

    assertThat(domNode, not(nullValue()));

    Node firstChild = domNode.getFirstChild();

    assertThat(firstChild, not(nullValue()));

    String nodeValue = firstChild.getNodeValue();

    assertThat(nodeValue, not(nullValue()));

    assertTrue(Base64.isBase64(nodeValue));

}

From source file:org.n52.wps.test.GrassIT.java

@Test
public void resultRawSHPIsBase64Encoded()
        throws IOException, ParserConfigurationException, SAXException, XmlException {

    URL resource = GrassIT.class.getResource("/Grass/v.buffer_request_out_shp_raw_base64.xml");
    XmlObject xmlPayload = XmlObject.Factory.parse(resource);

    String payload = xmlPayload.toString();
    String response = PostClient.sendRequest(wpsUrl, payload);
    assertThat(response, not(containsString("ExceptionReport")));

    assertTrue(Base64.isBase64(response));
}

From source file:org.n52.wps.test.GrassIT.java

@Test
public void resultRawGeoTiffIsBase64Encoded()
        throws IOException, ParserConfigurationException, SAXException, XmlException {

    XmlObject xmlPayload = createPayloadReplacingHostAndPort(
            "/Grass/r.resample_request_out_tiff_raw_base64.xml");

    String payload = xmlPayload.toString();
    String response = PostClient.sendRequest(wpsUrl, payload);
    assertThat(response, not(containsString("ExceptionReport")));

    assertTrue(Base64.isBase64(response));
}

From source file:org.openecomp.sdc.be.tosca.CsarUtils.java

private Either<ZipOutputStream, ActionStatus> collectAndWriteToScarDeploymentArtifacts(ZipOutputStream zip,
        Component component, List<ArtifactDefinition> aiiArtifactList) throws IOException {

    Collection<ArtifactDefinition> deploymentArtifactsToAdd = null;
    Collection<ArtifactDefinition> allArtifactsToAdd = new LinkedList<>();

    if (component.getComponentType() == ComponentTypeEnum.SERVICE) {
        Either<Service, StorageOperationStatus> getServiceResponse = serviceOperation
                .getService(component.getUniqueId());

        if (getServiceResponse.isLeft()) {
            Service service = getServiceResponse.left().value();

            if (!aiiArtifactList.isEmpty()) {
                deploymentArtifactsToAdd = service.getDeploymentArtifacts().values().stream()
                        .filter(e -> e.getGenerated() == null || !e.getGenerated())
                        .collect(Collectors.toList());
                allArtifactsToAdd.addAll(aiiArtifactList);
                allArtifactsToAdd.addAll(deploymentArtifactsToAdd);
            } else {
                allArtifactsToAdd.addAll(service.getDeploymentArtifacts().values());
            }//from w w w  . java2  s.  c  om
        }
    }

    if (!allArtifactsToAdd.isEmpty()) {

        for (ArtifactDefinition deploymentArtifactDefinition : allArtifactsToAdd) {
            String artifactFileName = deploymentArtifactDefinition.getArtifactName();
            byte[] payloadData = deploymentArtifactDefinition.getPayloadData();

            if (payloadData == null) {
                String esId = deploymentArtifactDefinition.getEsId();
                if (esId != null) {
                    Either<byte[], ActionStatus> fromCassandra = getFromCassandra(esId);

                    if (fromCassandra.isRight()) {
                        return Either.right(fromCassandra.right().value());
                    }
                    payloadData = fromCassandra.left().value();
                } else {
                    log.debug("Artifact {} payload not supplied in ArtifactDefinition and not found in DB",
                            artifactFileName);
                    continue;
                }
            }

            byte[] decodedPayload = null;

            if (Base64.isBase64(payloadData)) {
                // decodedPayload = Base64.getDecoder().decode(payloadData);
                decodedPayload = Base64.decodeBase64(payloadData);
            } else {
                decodedPayload = payloadData;
            }

            zip.putNextEntry(new ZipEntry(ARTIFACTS_PATH + artifactFileName));
            zip.write(decodedPayload);
        }
    }

    return Either.left(zip);
}

From source file:org.openecomp.sdc.common.util.GeneralUtility.java

public static boolean isBase64Encoded(byte[] data) {
    return Base64.isBase64(data);
}

From source file:org.openecomp.sdc.common.util.YamlToObjectConverter.java

public boolean isValidYaml(byte[] fileContents) {
    if (Base64.isBase64(fileContents)) {
        log.trace("Received Base64 data - decoding before validating...");
        fileContents = Base64.decodeBase64(fileContents);
    }//w  w w . ja va  2 s  .  c o  m
    try {
        Map<String, Object> mappedToscaTemplate = (Map<String, Object>) defaultYaml
                .load(new ByteArrayInputStream(fileContents));
    } catch (Exception e) {
        log.error("Failed to convert yaml file to object - yaml is invalid", e);
        return false;
    }
    return true;
}

From source file:org.sakaiproject.config.impl.StoredConfigService.java

private Object deSerializeValue(String value, String type, boolean secured) throws IllegalClassException {
    if (value == null || type == null) {
        return null;
    }//www.ja v  a2  s  . c  o m

    String string;

    if (secured) {
        // sanity check should be Base64 encoded
        if (Base64.isBase64(value)) {
            string = textEncryptor.decrypt(value);
        } else {
            log.warn(
                    "deSerializeValue() Invalid value found attempting to decrypt a secured property, check your secured properties");
            string = value;
        }
    } else {
        string = value;
    }

    Object obj;

    if (ServerConfigurationService.TYPE_STRING.equals(type)) {
        obj = string;
    } else if (ServerConfigurationService.TYPE_INT.equals(type)) {
        obj = Integer.valueOf(string);
    } else if (ServerConfigurationService.TYPE_BOOLEAN.equals(type)) {
        obj = Boolean.valueOf(string);
    } else if (ServerConfigurationService.TYPE_ARRAY.equals(type)) {
        obj = string.split(HibernateConfigItem.ARRAY_SEPARATOR);
    } else {
        throw new IllegalClassException("deSerializeValue() invalid TYPE, while deserializing");
    }
    return obj;
}

From source file:org.sonar.process.AesCipherTest.java

@Test
public void generateRandomSecretKey() {
    AesCipher cipher = new AesCipher(null);

    String key = cipher.generateRandomSecretKey();

    assertThat(StringUtils.isNotBlank(key)).isTrue();
    assertThat(Base64.isBase64(key.getBytes())).isTrue();
}