Example usage for javax.xml.bind DatatypeConverter parseBase64Binary

List of usage examples for javax.xml.bind DatatypeConverter parseBase64Binary

Introduction

In this page you can find the example usage for javax.xml.bind DatatypeConverter parseBase64Binary.

Prototype

public static byte[] parseBase64Binary(String lexicalXSDBase64Binary) 

Source Link

Document

Converts the string argument into an array of bytes.

Usage

From source file:com.squid.kraken.v4.api.core.ServiceUtils.java

public String decrypt(String key, String encryptedData) throws Exception {
    Key keySpec = new SecretKeySpec(key.getBytes(), ALGO);
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.DECRYPT_MODE, keySpec);
    byte[] decordedValue = DatatypeConverter.parseBase64Binary(encryptedData);
    byte[] decValue = c.doFinal(decordedValue);
    String decryptedValue = new String(decValue);
    return decryptedValue;
}

From source file:com.hp.application.automation.tools.octane.CIJenkinsServicesImpl.java

private List<ParameterValue> createParameters(AbstractProject project, JSONArray paramsJSON) {
    List<ParameterValue> result = new ArrayList<>();
    boolean parameterHandled;
    ParameterValue tmpValue;//from www  .j ava2  s  .c o m
    ParametersDefinitionProperty paramsDefProperty = (ParametersDefinitionProperty) project
            .getProperty(ParametersDefinitionProperty.class);
    if (paramsDefProperty != null) {
        for (ParameterDefinition paramDef : paramsDefProperty.getParameterDefinitions()) {
            parameterHandled = false;
            for (int i = 0; i < paramsJSON.size(); i++) {
                JSONObject paramJSON = paramsJSON.getJSONObject(i);
                if (paramJSON.has("name") && paramJSON.get("name") != null
                        && paramJSON.get("name").equals(paramDef.getName())) {
                    tmpValue = null;
                    switch (CIParameterType.fromValue(paramJSON.getString("type"))) {
                    case FILE:
                        try {
                            FileItemFactory fif = new DiskFileItemFactory();
                            FileItem fi = fif.createItem(paramJSON.getString("name"), "text/plain", false,
                                    paramJSON.getString("file"));
                            fi.getOutputStream()
                                    .write(DatatypeConverter.parseBase64Binary(paramJSON.getString("value")));
                            tmpValue = new FileParameterValue(paramJSON.getString("name"), fi);
                        } catch (IOException ioe) {
                            logger.warn("failed to process file parameter", ioe);
                        }
                        break;
                    case NUMBER:
                        tmpValue = new StringParameterValue(paramJSON.getString("name"),
                                paramJSON.get("value").toString());
                        break;
                    case STRING:
                        tmpValue = new StringParameterValue(paramJSON.getString("name"),
                                paramJSON.getString("value"));
                        break;
                    case BOOLEAN:
                        tmpValue = new BooleanParameterValue(paramJSON.getString("name"),
                                paramJSON.getBoolean("value"));
                        break;
                    case PASSWORD:
                        tmpValue = new PasswordParameterValue(paramJSON.getString("name"),
                                paramJSON.getString("value"));
                        break;
                    default:
                        break;
                    }
                    if (tmpValue != null) {
                        result.add(tmpValue);
                        parameterHandled = true;
                    }
                    break;
                }
            }
            if (!parameterHandled) {
                if (paramDef instanceof FileParameterDefinition) {
                    FileItemFactory fif = new DiskFileItemFactory();
                    FileItem fi = fif.createItem(paramDef.getName(), "text/plain", false, "");
                    try {
                        fi.getOutputStream().write(new byte[0]);
                    } catch (IOException ioe) {
                        logger.error("failed to create default value for file parameter '" + paramDef.getName()
                                + "'", ioe);
                    }
                    tmpValue = new FileParameterValue(paramDef.getName(), fi);
                    result.add(tmpValue);
                } else {
                    result.add(paramDef.getDefaultParameterValue());
                }
            }
        }
    }
    return result;
}

From source file:org.openhim.mediator.orchestration.ProvideAndRegisterOrchestrationActor.java

private void autoRegisterPatient() {
    String document = originalRequest.getDocument(); //is mime?
    if (document == null) { //else get from parsed message
        if (parsedRequest.getDocument() != null && parsedRequest.getDocument().size() >= 1) {
            document = parsedRequest.getDocument().get(0).getContent().get(0).toString();
            document = new String(DatatypeConverter.parseBase64Binary(document));
        }//from www  .  j av  a2  s.  c o  m
    }

    RegisterNewPatient registerNewPatient = buildRegistrationRequestFromCDA(document);
    if (registerNewPatient != null) {
        registerNewPatientHandler.tell(registerNewPatient, getSelf());
        sentNewRegistrationRequest = true;
    }
}

From source file:io.gravitee.management.service.impl.ApiServiceImpl.java

@Override
public ImageEntity getPicture(String apiId) {
    ApiEntity apiEntity = findById(apiId);
    ImageEntity imageEntity = new ImageEntity();
    if (apiEntity.getPicture() == null) {
        imageEntity.setType("image/png");
        try {/*from ww  w  .ja  v a  2  s . c  o  m*/
            imageEntity.setContent(IOUtils.toByteArray(new FileInputStream(defaultIcon)));
        } catch (IOException ioe) {
            LOGGER.error("Default icon for API does not exist", ioe);
        }

    } else {
        String[] parts = apiEntity.getPicture().split(";", 2);
        imageEntity.setType(parts[0].split(":")[1]);
        String base64Content = apiEntity.getPicture().split(",", 2)[1];
        imageEntity.setContent(DatatypeConverter.parseBase64Binary(base64Content));
    }

    return imageEntity;
}

From source file:com.microfocus.application.automation.tools.octane.CIJenkinsServicesImpl.java

private List<ParameterValue> createParameters(Job project, CIParameters ciParameters) {
    List<ParameterValue> result = new ArrayList<>();
    boolean parameterHandled;
    ParameterValue tmpValue;/* w w  w .  j a va 2  s.  c  o  m*/
    ParametersDefinitionProperty paramsDefProperty = (ParametersDefinitionProperty) project
            .getProperty(ParametersDefinitionProperty.class);
    if (paramsDefProperty != null) {
        Map<String, CIParameter> ciParametersMap = ciParameters.getParameters().stream()
                .collect(Collectors.toMap(CIParameter::getName, Function.identity()));
        for (ParameterDefinition paramDef : paramsDefProperty.getParameterDefinitions()) {
            parameterHandled = false;
            CIParameter ciParameter = ciParametersMap.remove(paramDef.getName());
            if (ciParameter != null) {
                tmpValue = null;
                switch (ciParameter.getType()) {
                case FILE:
                    try {
                        FileItemFactory fif = new DiskFileItemFactory();
                        FileItem fi = fif.createItem(ciParameter.getName(), "text/plain", false,
                                UUID.randomUUID().toString());
                        fi.getOutputStream()
                                .write(DatatypeConverter.parseBase64Binary(ciParameter.getValue().toString()));
                        tmpValue = new FileParameterValue(ciParameter.getName(), fi);
                    } catch (IOException ioe) {
                        logger.warn("failed to process file parameter", ioe);
                    }
                    break;
                case NUMBER:
                    tmpValue = new StringParameterValue(ciParameter.getName(),
                            ciParameter.getValue().toString());
                    break;
                case STRING:
                    tmpValue = new StringParameterValue(ciParameter.getName(),
                            ciParameter.getValue().toString());
                    break;
                case BOOLEAN:
                    tmpValue = new BooleanParameterValue(ciParameter.getName(),
                            Boolean.parseBoolean(ciParameter.getValue().toString()));
                    break;
                case PASSWORD:
                    tmpValue = new PasswordParameterValue(ciParameter.getName(),
                            ciParameter.getValue().toString());
                    break;
                default:
                    break;
                }
                if (tmpValue != null) {
                    result.add(tmpValue);
                    parameterHandled = true;
                }
            }
            if (!parameterHandled) {
                if (paramDef instanceof FileParameterDefinition) {
                    FileItemFactory fif = new DiskFileItemFactory();
                    FileItem fi = fif.createItem(paramDef.getName(), "text/plain", false, "");
                    try {
                        fi.getOutputStream().write(new byte[0]);
                    } catch (IOException ioe) {
                        logger.error("failed to create default value for file parameter '" + paramDef.getName()
                                + "'", ioe);
                    }
                    tmpValue = new FileParameterValue(paramDef.getName(), fi);
                    result.add(tmpValue);
                } else {
                    result.add(paramDef.getDefaultParameterValue());
                }
            }
        }

        //add parameters that are not defined in job
        for (CIParameter notDefinedParameter : ciParametersMap.values()) {
            tmpValue = new StringParameterValue(notDefinedParameter.getName(),
                    notDefinedParameter.getValue().toString());
            result.add(tmpValue);
        }
    }
    return result;
}

From source file:fr.paris.lutece.plugins.genericattributes.service.entrytype.AbstractEntryTypeImage.java

/**
 * Get a generic attributes response from a file item
 * @param fileItem The file item/*from w w  w.  j a va  2  s  .  c o m*/
 * @param entry The entry
 * @param bCreatePhysicalFile True to create the physical file associated
 *            with the file of the response, false otherwise. Note that the
 *            physical file will never be saved in the database by this
 *            method, like any other created object.
 * @return The created response
 */
private Response getResponseFromImage(String imageSource, Entry entry, boolean bCreatePhysicalFile) {
    Response response = new Response();
    response.setEntry(entry);

    File file = new File();
    DatatypeConverter.parseBase64Binary(imageSource);

    file.setTitle("crop_" + entry.getTitle());

    //file.setSize( 1222 );
    if (bCreatePhysicalFile) {
        file.setMimeType(FileSystemUtil.getMIMEType(file.getTitle()));

        PhysicalFile physicalFile = new PhysicalFile();
        physicalFile.setValue(DatatypeConverter.parseBase64Binary(imageSource));
        file.setPhysicalFile(physicalFile);
    }

    response.setFile(file);

    return response;
}

From source file:nz.co.jsrsolutions.tideservice.scraper.provider.EasyTideTideDataProvider.java

private EasyTidePageState getPageState(Parser parser)
        throws ParserException, TideDataProviderException, UnsupportedEncodingException {

    NodeList list = new NodeList();
    NodeFilter filter = new OrFilter(
            new AndFilter(new TagNameFilter("INPUT"), new HasAttributeFilter("ID", "__VIEWSTATE")),
            new AndFilter(new TagNameFilter("INPUT"), new HasAttributeFilter("ID", "__EVENTVALIDATION")));

    for (NodeIterator e = parser.elements(); e.hasMoreNodes();) {
        e.nextNode().collectInto(list, filter);
    }// ww  w  . jav a 2 s .  c  om

    if (list.size() != 2) {
        throw new TideDataProviderException(
                "Unable to find exactly one __VIEWSTATE tag and one __EVENTVALIDATION tag");
    }

    String viewState = null;
    String eventValidation = null;
    Node[] nodes = list.toNodeArray();
    for (Node node : nodes) {
        mLogger.debug(node);
        InputTag inputTag = (InputTag) node;
        if (inputTag.getAttribute("ID").compareTo("__VIEWSTATE") == 0) {
            viewState = inputTag.getAttribute("VALUE");
        }
        if (inputTag.getAttribute("ID").compareTo("__EVENTVALIDATION") == 0) {
            eventValidation = inputTag.getAttribute("VALUE");
        }
    }

    String decodedViewState = new String(DatatypeConverter.parseBase64Binary(viewState), "UTF-8");
    mLogger.debug(decodedViewState);

    return new EasyTidePageState(viewState, eventValidation);

}

From source file:de.ailis.xadrian.data.Complex.java

/**
 * Checks if the specified code is a valid template code.
 *
 * @param templateCode The template code to check.
 * @return True if code is valid, false if not.
 *///from   ww  w. j  av  a2 s . c  om
public static boolean isValidTemplateCode(final String templateCode) {
    try {
        // Decode base 64
        final byte[] data = DatatypeConverter.parseBase64Binary(templateCode.trim());

        final InputStream stream = new DynaByteInputStream(new ByteArrayInputStream(data));
        try {
            // Read complex settings
            final int settings = stream.read();
            final boolean hasSector = (settings & 1) == 1;
            final int gameNid = (settings >> 1) & 7;

            final Game game;
            try {
                game = GameFactory.getInstance().getGame(gameNid);
            } catch (final GameNotFoundException e) {
                return false;
            }

            // Read sector coordinates or sun power
            if (hasSector) {
                final int x = stream.read();
                final int y = stream.read();
                if (game.getSectorFactory().getSector(x, y) == null)
                    return false;
            } else {
                final int percent = stream.read();
                try {
                    game.getSunFactory().getSun(percent);
                } catch (final DataException e) {
                    return false;
                }
            }

            int factoryId;
            while ((factoryId = stream.read()) != 0) {
                final Factory factory = game.getFactoryFactory().getFactory(factoryId);
                if (factory == null)
                    return false;
                if (factory.isMine()) {
                    int yield;
                    while ((yield = stream.read()) != 0)
                        if (yield > 256)
                            return false;
                } else {
                    stream.read();
                }
            }

            return true;
        } finally {
            stream.close();
        }
    } catch (final Exception e) {
        return false;
    }
}

From source file:de.ailis.xadrian.data.Complex.java

/**
 * Creates a complex from the specified template code.
 *
 * @param templateCode//from  w  w w  .  j  a v a  2s  .c  o m
 *            The template code
 * @return The complex.
 */
public static Complex fromTemplateCode(final String templateCode) {
    try {
        // Decode base 64
        final byte[] data = DatatypeConverter.parseBase64Binary(templateCode.trim());

        final InputStream stream = new DynaByteInputStream(new ByteArrayInputStream(data));
        try {
            // Read complex settings
            final int settings = stream.read();
            final boolean hasSector = (settings & 1) == 1;
            final int gameNid = (settings >> 1) & 7;

            final Game game = GameFactory.getInstance().getGame(gameNid);
            final Complex complex = new Complex(game);

            // Read sector coordinates or sun power
            if (hasSector) {
                final int x = stream.read();
                final int y = stream.read();
                complex.setSector(game.getSectorFactory().getSector(x, y));
            } else {
                final int percent = stream.read();
                complex.setSuns(game.getSunFactory().getSun(percent));
            }

            int factoryId;
            while ((factoryId = stream.read()) != 0) {
                final Factory factory = game.getFactoryFactory().getFactory(factoryId);
                if (factory.isMine()) {
                    final List<Integer> yields = new ArrayList<Integer>();
                    int yield;
                    while ((yield = stream.read()) != 0)
                        yields.add(yield - 1);
                    complex.addFactory(new ComplexFactory(game, factory, yields));
                } else {
                    final int quantity = stream.read();
                    complex.addFactory(new ComplexFactory(game, factory, quantity, 0));
                }
            }

            return complex;
        } finally {
            stream.close();
        }
    } catch (final IOException e) {
        throw new TemplateCodeException(e.toString(), e);
    }
}

From source file:com.salesmanBuddy.Controllers.SalesmanBuddy.java

@Path("saveData") // Updated 10/23
//http://stackoverflow.com/questions/5999370/converting-between-nsdata-and-base64strings
/*/*from ww  w .j  a v a 2 s  .  c o m*/
 * try(InputStream is = new BufferedInputStream(request.getInputStream());){}
 * To try changing project to 1.7
 */
@PUT
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN })
public Response saveStringAsFileForCaptionEditor(@Context HttpServletRequest request,
        @DefaultValue("1") @QueryParam("base64") Integer base64,
        @DefaultValue("0") @QueryParam("mediaId") Integer mediaId,
        @DefaultValue("0") @QueryParam("popupId") Integer popupId,
        @DefaultValue("0") @QueryParam("subPopupId") Integer subPopupId) {
    String mimeType = request.getHeader("Content-Type");
    String extension = "";
    File file = null;
    String b64Bytes = "";
    FileOutputStream fos = null;
    try {
        extension = getFileTypeExtension(mimeType);
    } catch (Exception e) {
        return Response.status(Status.NOT_ACCEPTABLE).entity(
                "there was an exception getting file type: " + mimeType + ", error: " + e.getLocalizedMessage())
                .build();
    }
    if (base64 == 1) {
        try {// working 10/25
            file = File.createTempFile(this.dao.randomAlphaNumericOfLength(15), extension);
            file.deleteOnExit();
            fos = new FileOutputStream(file);
            InputStream is = new BufferedInputStream(request.getInputStream());
            b64Bytes = IOUtils.toString(is);
            byte[] fileBytes = DatatypeConverter.parseBase64Binary(b64Bytes);
            IOUtils.write(fileBytes, fos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } else {
        try {// untested
            file = File.createTempFile(this.dao.randomAlphaNumericOfLength(15), extension);
            file.deleteOnExit();
            fos = new FileOutputStream(file);
            InputStream is = new BufferedInputStream(request.getInputStream());
            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
            byte[] buffer = new byte[1024];
            for (int read = 0; (read = is.read(buffer)) != -1;) {
                messageDigest.update(buffer, 0, read);
                fos.write(buffer, 0, read);
            }
            fos.close();
            //            byte [] sha1bytes = messageDigest.digest();
            //            sha1 = DatatypeConverter.printBase64Binary(sha1bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } finally {
            if (fos != null)
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }

    GenericEntity<String> entity = new GenericEntity<String>(
            this.captionEditorDAO.saveFileToS3ForCaptionEditor(file, extension, mediaId, popupId, subPopupId)) {
    };
    file.delete();
    return Response.ok(entity).build();
}