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:org.ecocean.media.MediaAsset.java

public void copyInBase64(String b64) throws IOException {
    if (b64 == null)
        throw new IOException("copyInBase64() null string");
    byte[] imgBytes = new byte[100];
    try {/*from   w ww . ja v a  2s .  co m*/
        imgBytes = DatatypeConverter.parseBase64Binary(b64);
    } catch (IllegalArgumentException ex) {
        throw new IOException("copyInBase64() could not parse: " + ex.toString());
    }
    File file = (this.localPath() != null) ? this.localPath().toFile()
            : File.createTempFile("b64-" + Util.generateUUID(), ".tmp");
    FileOutputStream stream = new FileOutputStream(file);
    try {
        stream.write(imgBytes);
    } finally {
        stream.close();
    }
    if (file.exists()) {
        this.copyIn(file);
    } else {
        throw new IOException("copyInBase64() could not write " + file);
    }
}

From source file:org.fejoa.library.messages.PublicCryptoEnvelope.java

static public InputStream decryptStream(JSONObject header, InputStream inputStream, ContactPrivate contact,
        FejoaContext context) throws JSONException, IOException, CryptoException {
    String keyId = header.getString(PUBLIC_KEY_ID_KEY);
    CryptoSettings.Asymmetric asymSettings = JsonCryptoSettings
            .asymFromJson(header.getJSONObject(PUBLIC_KEY_SETTINGS_KEY));
    byte[] iv = DatatypeConverter.parseBase64Binary(header.getString(IV_KEY));
    byte[] encSymKey = DatatypeConverter.parseBase64Binary(header.getString(ENC_SYMMETRIC_KEY_KEY));
    CryptoSettings.Symmetric symSettings = JsonCryptoSettings
            .symFromJson(header.getJSONObject(SYMMETRIC_SETTINGS_KEY));

    ICryptoInterface crypto = context.getCrypto();
    KeyPairData keyPairData = contact.getEncryptionKey(keyId);
    if (keyPairData == null)
        throw new IOException("key not found");
    byte[] symKey = crypto.decryptAsymmetric(encSymKey, keyPairData.getKeyPair().getPrivate(), asymSettings);
    SecretKey key;/*  www.  ja  va  2 s.c  o m*/
    try {
        key = CryptoHelper.secretKey(symKey, symSettings);
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }

    return crypto.decryptSymmetric(inputStream, key, iv, symSettings);
}

From source file:org.fejoa.library.messages.PublicCryptoEnvelope.java

static public byte[] decrypt(JSONObject header, InputStream inputStream, ContactPrivate contact,
        FejoaContext context) throws JSONException, IOException, CryptoException {
    String keyId = header.getString(PUBLIC_KEY_ID_KEY);
    CryptoSettings.Asymmetric asymSettings = JsonCryptoSettings
            .asymFromJson(header.getJSONObject(PUBLIC_KEY_SETTINGS_KEY));
    byte[] iv = DatatypeConverter.parseBase64Binary(header.getString(IV_KEY));
    byte[] encSymKey = DatatypeConverter.parseBase64Binary(header.getString(ENC_SYMMETRIC_KEY_KEY));
    CryptoSettings.Symmetric symSettings = JsonCryptoSettings
            .symFromJson(header.getJSONObject(SYMMETRIC_SETTINGS_KEY));

    ICryptoInterface crypto = context.getCrypto();
    KeyPairData keyPairData = contact.getEncryptionKey(keyId);
    if (keyPairData == null)
        throw new IOException("key not found");
    byte[] symKey = crypto.decryptAsymmetric(encSymKey, keyPairData.getKeyPair().getPrivate(), asymSettings);
    SecretKey key;/*from w w w  .  j  a va  2s  .  c  o m*/
    try {
        key = CryptoHelper.secretKey(symKey, symSettings);
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    InputStream cryptoStream = crypto.decryptSymmetric(inputStream, key, iv, symSettings);
    StreamHelper.copy(cryptoStream, outputStream);
    return outputStream.toByteArray();
}

From source file:org.gathe.verge.uno.ODT2PDFConverter.java

public void run() {

    System.setProperty("javax.net.ssl.trustStore", "/opt/myKeystore");
    System.setProperty("javax.net.ssl.trustStorePassword", "keys$%");

    FileInputStream is = null;/*from   w w w.  j a  v a 2  s . c om*/
    try {
        XComponentContext xComponentContext = Bootstrap.bootstrap();
        //       XComponentContext xComponentContext = BootstrapSocketConnector.bootstrap(oooExeFolder);
        XMultiComponentFactory xMCF = xComponentContext.getServiceManager();

        HashMap<String, ArrayList<HashMap<String, String>>> data = new HashMap<>();
        HashMap<String, String> fields = new HashMap<>();

        String json = this.getParameters(); //"{\"lastname\":\"\",\"firstname\":\"\",\"middlename\":\"\",\"table-ege\":[{\"subject\":\"Physics\",\"Score\":\"100\"},{\"subject\":\"Chemistry\",\"Score\":\"95\"}]}";

        JSONParser parser = new JSONParser();
        System.out.println(json);
        JSONObject jsonObj = (JSONObject) parser.parse(json);
        for (Object jsonKey : jsonObj.keySet()) {
            if (("" + jsonKey).startsWith("table-")) {
                ArrayList<HashMap<String, String>> tableContent = new ArrayList<>();
                String tableName = ("" + jsonKey).substring(6);
                JSONArray arr = (JSONArray) jsonObj.get(jsonKey);
                HashMap<String, String> row;
                for (int c = 0; c < arr.size(); c++) {
                    row = new HashMap<>();
                    JSONObject jobj = (JSONObject) arr.get(c);
                    for (Object rowKey : jobj.keySet()) {
                        String rowKeyStr = "" + rowKey;
                        String rowValue = "" + jobj.get(rowKey);
                        row.put(rowKeyStr.toUpperCase(), rowValue);
                    }
                    tableContent.add(row);
                }
                data.put(tableName.toUpperCase(), tableContent);
            } else {
                String jsonValue = "" + jsonObj.get(jsonKey);
                fields.put(("" + jsonKey).toUpperCase(), jsonValue);
                System.out.println(jsonKey + ":" + jsonValue);
            }
        }

        //load file
        Object oDesktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xComponentContext);
        XComponentLoader xCompLoader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class,
                oDesktop);
        String url = this.getTemplateName();//"file:///devel/LOConnector/declaration_bachelor.odt";

        PropertyValue[] loadProperties = new PropertyValue[1];
        //        loadProperties[0] = new PropertyValue();
        //        loadProperties[0].Name = "Hidden";
        //        loadProperties[0].Value = new Boolean(false);
        loadProperties[0] = new PropertyValue();
        loadProperties[0].Name = "ReadOnly";
        loadProperties[0].Value = new Boolean(false);
        Object document = xCompLoader.loadComponentFromURL(url, "_blank", 0, loadProperties);

        XTextDocument xTextDocument = UnoRuntime.queryInterface(XTextDocument.class, document);

        XTextFieldsSupplier fieldsSupplier = UnoRuntime.queryInterface(XTextFieldsSupplier.class, document);
        //        
        XNameAccess xNameAccess = fieldsSupplier.getTextFieldMasters();
        for (String element : fields.keySet()) {
            if (element.startsWith("#"))
                continue;
            System.out.println(element);
            String value = fields.get(element);
            System.out.println(value);
            if (value != null) {
                String name = "com.sun.star.text.FieldMaster.User." + element.toUpperCase();
                if (xNameAccess.hasByName(name)) {
                    Object fieldObj = xNameAccess.getByName(name);
                    XPropertySet field = UnoRuntime.queryInterface(XPropertySet.class, fieldObj);
                    String oldValue = field.getPropertyValue("Content").toString();
                    System.out.println(oldValue);
                    if (oldValue.startsWith("#")) {
                        if (value.equalsIgnoreCase("true")) {
                            value = "1";
                        }
                        if (value.equalsIgnoreCase("false")) {
                            value = "0";
                        }
                        String[] values = oldValue.substring(1).split("/");
                        boolean flag = false;
                        for (String value2 : values) {
                            String[] entry = value2.split("=");
                            if (entry.length == 1) {
                                String[] entry2 = new String[2];
                                entry2[0] = entry[0];
                                entry2[1] = "";
                                entry = entry2;
                            }
                            System.out.println("Comparing " + entry[0] + " : " + entry[1] + " with " + value);
                            if (Integer.parseInt(entry[0]) == Integer.parseInt(value)) {
                                flag = true;
                                value = entry[1];
                                break;
                            }
                        }
                        if (!flag)
                            value = "<??>";
                    }
                    field.setPropertyValue("Content", value);
                }
            }
        }

        XTextTablesSupplier tablesSupplier = UnoRuntime.queryInterface(XTextTablesSupplier.class, document);

        //fill the tables
        XNameAccess allTables = tablesSupplier.getTextTables();
        for (String tableName : data.keySet()) {
            if (!allTables.hasByName(tableName)) {
                continue;
            }
            Object retrievedTableObj = allTables.getByName(tableName);
            ArrayList<HashMap<String, String>> dataSubset = data.get(tableName);

            if (dataSubset.size() == 0) {
                //remove empty table
                XTextDocument textDocument = UnoRuntime.queryInterface(XTextDocument.class, document);
                XText text = textDocument.getText();
                XTextContent tableContentText = UnoRuntime.queryInterface(XTextContent.class,
                        retrievedTableObj);
                text.removeTextContent(tableContentText);
                continue;
            }
            XTextTable retrievedTable = UnoRuntime.queryInterface(XTextTable.class, retrievedTableObj);
            XCellRange retrievedTableCells = UnoRuntime.queryInterface(XCellRange.class, retrievedTableObj);
            int rowsCount = retrievedTable.getRows().getCount();
            int colsCount = retrievedTable.getColumns().getCount();

            ArrayList<String> rowNumbers = new ArrayList<String>();
            ArrayList<HashMap<String, String>> fieldsLocations = new ArrayList<HashMap<String, String>>();
            ArrayList<String> rowLength = new ArrayList<String>();

            //get row numbers with referenced fields
            int maxRow = 0;
            int maxLen = 0;
            for (int row = 0; row < rowsCount; row++) {
                boolean found = false;
                HashMap<String, String> fieldsAtRow = new HashMap<String, String>();
                int col = 0;
                for (col = 0; col < colsCount; col++) {
                    System.out.println("Reading cell " + col + ":" + row);
                    try {
                        XCell cell = retrievedTableCells.getCellByPosition(col, row);
                        XText cellText = UnoRuntime.queryInterface(XText.class, cell);
                        String val = cellText.getString();
                        if (val.startsWith("#")) {
                            fieldsAtRow.put("" + col, val.substring(1));
                            found = true;
                        }
                    } catch (Exception e) {
                        break;
                    }
                }
                if (found) {
                    rowNumbers.add("" + row);
                    fieldsLocations.add(fieldsAtRow);
                    rowLength.add("" + col);
                    if (row > maxRow)
                        maxRow = row;
                    if (col > maxLen)
                        maxLen = col;
                }
            }
            maxRow++;

            XController xController = xTextDocument.getCurrentController();
            XTransferableSupplier xTransferableSupplier = UnoRuntime.queryInterface(XTransferableSupplier.class,
                    xController);

            //Fill the table below the bottom line
            int tableRow = maxRow;
            for (HashMap<String, String> dataRow : dataSubset) {
                //                    if (tableRow != 0) {
                System.out.println("Adding row " + maxRow);
                retrievedTable.getRows().insertByIndex(maxRow, 1);
                maxRow++;
            }

            for (HashMap<String, String> dataRow : dataSubset) {
                //merging cells
                System.out.println("Datarow: " + dataRow);
                int rowId = 0;
                if (dataRow.containsKey("%"))
                    rowId = Integer.parseInt("" + dataRow.get("%"));
                int rowLen = Integer.parseInt(rowLength.get(rowId));
                if (dataRow.containsKey("$")) {
                    System.out.println("MERGING CELLS");
                    int left = maxLen;
                    int positionX = 0;
                    int positionY = tableRow;
                    String[] dataRowSize = dataRow.get("$").split(",");
                    int newLen = 0;
                    for (String dataRowSizeElement : dataRowSize) {
                        System.out.println("PROCESSING: " + dataRowSizeElement);
                        int horSpan;
                        if (dataRowSizeElement.equals("*"))
                            horSpan = left;
                        else
                            horSpan = Integer.parseInt(dataRowSizeElement);
                        String startAddress = String.valueOf(Character.toChars(positionX + 65))
                                + (positionY + 1);
                        XTextTableCursor textTableCursor = retrievedTable.createCursorByCellName(startAddress);
                        if (horSpan > 1)
                            textTableCursor.goRight((short) (horSpan - 1), true);
                        textTableCursor.mergeRange();
                        left -= horSpan;
                        newLen++;
                        if (left <= 0)
                            break;
                    }
                    rowLen = newLen;
                }

                System.out.println("Extracting range for 0:" + rowNumbers.get(rowId) + ":" + (rowLen - 1) + ":"
                        + rowNumbers.get(rowId));
                XCellRange templateRow = retrievedTableCells.getCellRangeByPosition(0,
                        Integer.parseInt(rowNumbers.get(rowId)), rowLen - 1,
                        Integer.parseInt(rowNumbers.get(rowId)));
                XSelectionSupplier xSelectionSupplier = UnoRuntime.queryInterface(XSelectionSupplier.class,
                        xController);
                xSelectionSupplier.select(templateRow);
                XTransferable transferable = xTransferableSupplier.getTransferable();
                System.out.println("Getting cellRange 0:" + tableRow + ":" + (rowLen - 1) + ":" + tableRow);
                XCellRange newRow = retrievedTableCells.getCellRangeByPosition(0, tableRow, rowLen - 1,
                        tableRow);
                xSelectionSupplier.select(newRow);
                xTransferableSupplier.insertTransferable(transferable);
                //                    }
                for (int tableCol = 0; tableCol < rowLen; tableCol++) {

                    HashMap<String, String> rowMetadata = fieldsLocations.get(rowId);
                    if (rowMetadata.containsKey("" + tableCol)) {
                        String fieldId = rowMetadata.get("" + tableCol);
                        String dataItem = dataRow.get(fieldId);
                        System.out.println("Retrieving cell:" + tableCol + ":" + tableRow);
                        XCell cell = retrievedTableCells.getCellByPosition(tableCol, tableRow);
                        System.out.println(
                                "Setting to cell " + tableCol + ":" + tableRow + " value: " + dataItem);
                        XText cellText = UnoRuntime.queryInterface(XText.class, cell);
                        cellText.setString(dataItem);
                    }
                }
                //                    if (tableRow != 0) {
                tableRow++;
                //                    }
            }
            for (int i = rowNumbers.size() - 1; i >= 0; i--) {
                retrievedTable.getRows().removeByIndex(Integer.parseInt(rowNumbers.get(i)), 1);
            }
        }

        //show/hide frames
        XTextFramesSupplier framesSupplier = UnoRuntime.queryInterface(XTextFramesSupplier.class, document);
        XNameAccess frames = framesSupplier.getTextFrames();
        XTextDocument textDocument = UnoRuntime.queryInterface(XTextDocument.class, document);
        XText text = textDocument.getText();
        for (String fieldName : fields.keySet()) {
            if (!fieldName.startsWith("#")) {
                continue;
            }
            String fieldName2 = fieldName.substring(1);
            String value = fields.get(fieldName);
            if (frames.hasByName(fieldName2)) {
                System.out.println("Checking frame " + fieldName2);
                if (value.trim().equalsIgnoreCase("0")) {
                    System.out.println("Hiding");
                    Object frameContent = frames.getByName(fieldName2);
                    XTextContent frameContentText = UnoRuntime.queryInterface(XTextContent.class, frameContent);
                    text.removeTextContent(frameContentText);
                }
            }
        }

        //update graphic objects
        XTextGraphicObjectsSupplier goSupplier = UnoRuntime.queryInterface(XTextGraphicObjectsSupplier.class,
                document);
        XNameAccess graphicsObjects = goSupplier.getGraphicObjects();
        for (String objName : fields.keySet()) {
            if (!objName.startsWith("@"))
                continue;
            String value = fields.get(objName); //encoded binary image
            byte[] imageData = DatatypeConverter.parseBase64Binary(value);
            File temp = File.createTempFile("image", ".jpg", new File("/tmp"));
            FileOutputStream fos = null;
            fos = new FileOutputStream(temp);
            fos.write(imageData);
            fos.flush();
            fos.close();
            String newURL = temp.getCanonicalPath();
            String goName = objName.substring(1);
            if (graphicsObjects.hasByName(goName)) {
                XPropertySet graphicObject = UnoRuntime.queryInterface(XPropertySet.class,
                        graphicsObjects.getByName(goName));
                graphicObject.setPropertyValue("GraphicURL", "file://" + newURL);
            }
        }

        //transform file

        //save file
        String sSaveURL = "file:///tmp/" + this.getSessionID() + ".pdf";

        XStorable xStorable = (XStorable) UnoRuntime.queryInterface(XStorable.class, document);
        PropertyValue[] propertyValue = new PropertyValue[2];
        propertyValue[0] = new PropertyValue();
        propertyValue[0].Name = "Overwrite";
        propertyValue[0].Value = new Boolean(true);
        propertyValue[1] = new PropertyValue();
        propertyValue[1].Name = "FilterName";
        propertyValue[1].Value = "writer_pdf_Export";

        xStorable.storeToURL(sSaveURL, propertyValue);
        XComponent component = (XComponent) UnoRuntime.queryInterface(XComponent.class, document);
        component.dispose();

        byte[] key = this.getSessionID().getBytes("utf-8");
        File file = new File("/tmp/" + this.getSessionID() + ".pdf");
        is = new FileInputStream(file);
        long length = file.length();

        byte[] bytes = new byte[(int) length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }
        System.out.println("Here");
        jedis.set(key, bytes);
        jedis.expire(key, 30 * 60); //30 minutes to expire
        is.close();
        file.delete();

        //            String url2 = this.getCallbackURL();
        //            if (url2.trim().length()!=0) {
        //              url2 = url2.replace("~SESSION~", this.getSessionID());
        //              URL urlx;
        //              try {
        //                  urlx = new URL(url2);
        //                  urlx.openStream();
        //              } catch (IOException ex) {
        //                  Logger.getLogger(ODT2PDFConverter.class.getName()).log(Level.SEVERE, null, ex);
        //              }
        //            }
        //        XCloseable xCloseable = (XCloseable) UnoRuntime.queryInterface(XCloseable.class, document);
        //        if (xCloseable!=null) {
        //            xCloseable.close(false);
        //        }

    } catch (IOException | Exception | ParseException | BootstrapException ex) {
        Logger.getLogger(ODT2PDFConverter.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException ex) {
            Logger.getLogger(ODT2PDFConverter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.jboss.fuse.rhaccess.servlet.SupportServlet.java

private API prepareApiInvocation(JSONObject jsonObject, String authToken) throws JSONException {

    String decodedCredentials = new String(DatatypeConverter.parseBase64Binary(authToken));
    String[] splitCredentials = decodedCredentials.split(":");
    String username = null;/*from w ww  .ja v a 2 s .  co m*/
    String password = null;
    if (splitCredentials != null) {
        if (splitCredentials.length < 2) {
            log.warn("Problem with authentication credentials: [{}]", decodedCredentials);
            throw new JSONException("Problem with authentication credentials");
        }
        if (splitCredentials[0] != null) {
            username = splitCredentials[0];
        }
        if (splitCredentials[1] != null) {
            password = splitCredentials[1];
        }
    }
    Config config = new Config();
    return new API(username, password, config.getURL(), config.getProxyUser(), config.getProxyPassword(),
            config.getProxyURL(), config.getProxyPort(), config.getUserAgent(), config.isDevel());

}

From source file:org.jevis.rest.Config.java

public static JEVisDataSource getJEVisDS(HttpHeaders httpHeaders) throws AuthenticationException {
    if (httpHeaders.getRequestHeader("authorization") == null
            || httpHeaders.getRequestHeader("authorization").isEmpty()) {
        throw new AuthenticationException("Authorization header is missing");
    }//from   w ww. j a v a2  s.c om
    String auth = httpHeaders.getRequestHeader("authorization").get(0);
    if (auth != null && !auth.isEmpty()) {
        auth = auth.replaceFirst("[Bb]asic ", "");

        System.out.println("Auth: '" + auth + "'");
        byte[] decoded2 = DatatypeConverter.parseBase64Binary(auth);
        //            if (Base64.isBase64(auth.getBytes())) {
        byte[] decoded = Base64.decodeBase64(auth);
        String debugFuck = ("1: " + Arrays.toString(decoded2) + "\n" + "2: " + Arrays.toString(decoded) + "\n"
                + "Equal: " + Arrays.equals(decoded, decoded2));

        try {
            //InitialContext()
            String decodeS = (new String(decoded, "UTF-8"));
            String decodeS2 = (new String(decoded));

            //                String decodeS = (new String(decoded, "UTF-8") + "\n");
            String[] dauth = decodeS.split(":");
            if (dauth.length == 2) {

                String username = dauth[0];
                String password = dauth[1];
                //                    String username = "Sys Admin";
                //                    String password = "OpenJEVis2016";

                System.out.println("Username: '" + username + "'   PW: '" + password + "'");
                try {
                    JEVisDataSource ds = Config.getDS(username, password);

                    try {
                        if (ds.connect(username, password)) {
                            return ds;
                        } else {
                            //                                throw new AuthenticationException("Username/Password is not correct.1");
                            throw ErrorBuilder.ErrorBuilder(Response.Status.UNAUTHORIZED.getStatusCode(), 2001,
                                    "Username/Password is not correct.");
                        }
                    } catch (JEVisException jex) {
                        throw ErrorBuilder.ErrorBuilder(Response.Status.UNAUTHORIZED.getStatusCode(), 2002,
                                "Username/Password is not correct.");
                    }

                } catch (JEVisException ex) {
                    //                        throw new AuthenticationException("Could not connect to Database:\n" + ex);
                    throw ErrorBuilder.ErrorBuilder(Response.Status.UNAUTHORIZED.getStatusCode(), 2001,
                            "Username/Password is not correct.");
                }
            } else {
                //                    throw new AuthenticationException("The HTML authorization header is not correct formate");
                throw ErrorBuilder.ErrorBuilder(Response.Status.BAD_REQUEST.getStatusCode(), 2002,
                        "The HTML authorization header is not correct formate");
            }
        } catch (UnsupportedEncodingException uee) {
            //                throw new AuthenticationException("The HTML authorization header is not in Base64");
            throw ErrorBuilder.ErrorBuilder(Response.Status.BAD_REQUEST.getStatusCode(), 2003,
                    "The HTML authorization header is not in Base64");
        }
        //            } else {
        //                throw ErrorBuilder.ErrorBuilder(Response.Status.BAD_REQUEST.getStatusCode(), 2003, "The HTML authorization header is not in Base64");
        //            }
    } else {
        //            throw new AuthenticationException("The HTML authorization header is missing or emty");
        throw ErrorBuilder.ErrorBuilder(Response.Status.BAD_REQUEST.getStatusCode(), 2004,
                "The HTML authorization header is missing or emty");
    }

}

From source file:org.ohmage.validator.SurveyResponseValidators.java

/**
 * Validates that a "images" value was a valid JSON object whose keys were
 * the image IDs (UUIDs) and values were BASE64-encoded images. It then 
 * returns the map of the IDs to BufferedImages.
 * //from w  w w .  jav  a 2 s .  c  o m
 * @param value The value to be validated.
 * 
 * @return The map of image IDs to Images.
 * 
 * @throws ValidationException The value was not valid JSON, an image's ID
 *                         was not a valid UUID, or an image's contents
 *                         was not a valid BASE64-encoded image.
 */
public static Map<UUID, Image> validateImages(final String value) throws ValidationException {

    if (StringUtils.isEmptyOrWhitespaceOnly(value)) {
        return null;
    }

    JSONObject imagesJson;
    try {
        imagesJson = new JSONObject(value);
    } catch (JSONException e) {
        throw new ValidationException(ErrorCode.SURVEY_INVALID_IMAGES_VALUE,
                "The images parameter was not valid JSON: " + value, e);
    }

    Map<UUID, Image> results = new HashMap<UUID, Image>();

    Iterator<?> imageIds = imagesJson.keys();
    int numImageIds = imagesJson.length();
    for (int i = 0; i < numImageIds; i++) {
        UUID imageUuid;
        String imageId = (String) imageIds.next();

        try {
            imageUuid = UUID.fromString(imageId);
        } catch (IllegalArgumentException e) {
            throw new ValidationException(ErrorCode.SURVEY_INVALID_IMAGES_VALUE,
                    "An image's ID is not a valid UUID: " + imageId, e);
        }

        Image image;
        try {
            image = ImageValidators.validateImageContents(imageUuid,
                    DatatypeConverter.parseBase64Binary(imagesJson.getString(imageId)));
        } catch (JSONException e) {
            throw new ValidationException(ErrorCode.SURVEY_INVALID_IMAGES_VALUE,
                    "The image's contents in the JSON was not a string.", e);
        } catch (IllegalArgumentException e) {
            throw new ValidationException(ErrorCode.SURVEY_INVALID_IMAGES_VALUE,
                    "The image's contents were not BASE64.", e);
        }

        results.put(imageUuid, image);
    }

    return results;
}

From source file:org.opendaylight.aaa.encrypt.AAAEncryptionServiceImpl.java

@Override
public String decrypt(String encData) {
    if (key == null || encData == null || encData.length() == 0) {
        LOG.warn("String {} was not decrypted.", encData);
        return encData;
    }/*from  www  .java2s. c  o  m*/
    try {
        byte[] cryptobytes = DatatypeConverter.parseBase64Binary(encData);
        byte[] clearbytes = decryptCipher.doFinal(cryptobytes);
        return new String(clearbytes);
    } catch (IllegalBlockSizeException | BadPaddingException e) {
        LOG.error("Failed to decrypt encoded data", e);
    }
    return encData;
}

From source file:org.openmrs.module.emrapi.person.image.EmrPersonImageServiceImpl.java

@Override
public PersonImage savePersonImage(PersonImage personImage) {
    Person person = personImage.getPerson();
    String base64EncodedImage = personImage.getBase64EncodedImage();

    if (base64EncodedImage == null || base64EncodedImage.isEmpty())
        return personImage;

    try {/*from   w  ww  .java 2 s.com*/
        File imageFile = new File(String.format("%s/%s.%s",
                emrApiProperties.getPersonImageDirectory().getAbsolutePath(), person.getUuid(), imageFormat));

        byte[] decodedBytes = DatatypeConverter.parseBase64Binary(base64EncodedImage);
        BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(decodedBytes));
        ImageIO.write(bufferedImage, imageFormat, imageFile);
        bufferedImage.flush();

        personImage.setSavedImage(imageFile);
        log.info("Successfully created patient image at " + imageFile);

    } catch (Exception e) {
        log.error("Update patient image failed for : " + person);
        throw new APIException("Could not save patient image", e);
    }
    return personImage;
}

From source file:org.raml.parser.visitor.SchemaCompiler.java

public static String[] decodeIncludePath(String encodedSchema) {
    int idx = encodedSchema.indexOf(SEPARATOR);
    if (idx == -1) {
        throw new IllegalArgumentException("Invalid include encoded schema.");
    }/*www . ja v  a2  s  .  c o  m*/
    String base64Path = encodedSchema.substring(0, idx);
    String includePath = new String(DatatypeConverter.parseBase64Binary(base64Path));
    String schema = encodedSchema.substring(idx + SEPARATOR.length(), encodedSchema.length());
    return new String[] { includePath, schema };
}