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.mobicage.rogerthat.xmpp.CallBackApiXMPPListener.java

/**
 * Establish an XMPP connection to XmppService and listen for Rogerthat API callbacks.
 *///from   w  w  w. j a v  a 2s  .  c o  m
public void startListening() {

    if (connectionThread != null) {
        throw new RuntimeException("Previous connection has not yet been closed!");
    }

    if (xmppUsername == null || xmppService == null || xmppPassword == null || sik == null)
        throw new RuntimeException("Not enough information present to setup an xmpp connection");

    final ConnectionListener connectionListener = new ConnectionListener() {
        @Override
        public void reconnectionSuccessful() {
            log.info("Reconnection to jabber server succeeded.");
            status = XmppConnectionStatus.Connected;
        }

        @Override
        public void reconnectionFailed(Exception e) {
            log.info("Reconnection to jabber server failed.");
        }

        @Override
        public void reconnectingIn(int seconds) {
            log.info("Reconnecting to jabber in " + seconds + " seconds ...");
            status = XmppConnectionStatus.Reconnecting;
        }

        @Override
        public void connectionClosedOnError(Exception e) {
            log.info("Connection closed to jabber due to " + e.toString());
        }

        @Override
        public void connectionClosed() {
            log.info("Connection to jabber closed.");
        }
    };

    tasks.clear();

    connectionThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                while (true) {
                    Runnable task = tasks.take();
                    task.run();
                }
            } catch (StopListeningException e) {
                disconnect(connectionListener);
                status = XmppConnectionStatus.Closed;
                statusLine = "";
            } catch (Throwable e) {
                disconnect(connectionListener);
                status = XmppConnectionStatus.Closed;
                statusLine = "Connection interrupted.";
            } finally {
                connectionThread = null;
            }
        }
    });
    connectionThread.setName("Rogerthat callback listener");
    connectionThread.setDaemon(true);
    connectionThread.start();

    tasks.add(new Runnable() {
        @Override
        public void run() {
            ConnectionConfiguration conf = new ConnectionConfiguration(xmppService);

            status = XmppConnectionStatus.Connecting;

            log.info("Connecting to jabber server ...");
            conn = new XMPPConnection(conf);
            try {
                conn.connect();
            } catch (XMPPException e) {
                status = XmppConnectionStatus.ConnectionFailed;
                statusLine = "Failed to reach Rogerthat servers.\n" + e.getMessage();
                conn = null;
                connectionThread = null;
                if (onConnectionFailed != null)
                    try {
                        onConnectionFailed.run();
                    } catch (Throwable t) {
                        log.log(Level.WARNING, "Failure in onConnectionFailed handler.", t);
                    }
                throw new RuntimeException(e); // Stop thread.
            }

            if (onConnected != null)
                try {
                    onConnected.run();
                } catch (Throwable t) {
                    log.log(Level.WARNING, "Failure in onConnected handler.", t);
                }

            conn.addConnectionListener(connectionListener);

            SASLAuthentication.supportSASLMechanism("PLAIN", 0);

            PacketFilter filter = new PacketFilter() {
                @Override
                public boolean accept(Packet packet) {
                    boolean accept = packet instanceof Message
                            && ROGERTHAT_CALLBACK_BOT.equals(packet.getFrom());
                    if (!accept)
                        log.info("Dropping packet:\n" + packet.toXML());
                    return accept;
                }
            };

            conn.addPacketListener(new PacketListener() {
                @Override
                public void processPacket(Packet packet) {
                    log.info("Processing packet:\n" + packet.toXML());
                    if (!(packet instanceof Message)) {
                        log.info("Ignoring non message packet.");
                        return;
                    }
                    Message message = (Message) packet;
                    PacketExtension extension = packet.getExtension("call", "mobicage:comm");
                    if (extension == null || !(extension instanceof CallbackRequestExtension)) {
                        log.info("Ignoring incomplete packet.");
                        return;
                    }
                    CallbackRequestExtension call = (CallbackRequestExtension) extension;
                    if (!sik.equals(call.getSik())) {
                        log.info("Ignoring packet with incorrect sik.");
                        return;
                    }
                    String json;
                    try {
                        json = new String(DatatypeConverter.parseBase64Binary(call.getBase64Body()), "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        log.log(Level.WARNING, "Could not decode base64 packet.", e);
                        return;
                    }
                    final JSONObject request = (JSONObject) JSONValue.parse(json);

                    if (logTraffic)
                        log.info(String.format("Incoming Rogerthat API Callback.\nSIK: %s\n\n%s", sik, json));

                    final String id = (String) request.get("id");

                    if (callbackDedup != null) {
                        byte[] response = callbackDedup.getResponse(id);
                        if (response != null) {
                            Message resultMessage = new Message(message.getFrom());
                            resultMessage.setFrom(message.getTo());
                            resultMessage.addExtension(new CallbackResponseExtension(sik,
                                    DatatypeConverter.printBase64Binary(response)));
                            log.info("Sending message:\n" + resultMessage.toXML());
                            conn.sendPacket(resultMessage);
                            return;
                        }
                    }

                    final JSONObject result = new JSONObject();
                    final RequestContext requestContext = new RequestContext(id, sik);
                    try {
                        processor.process(request, result, requestContext);
                    } finally {
                        try {
                            StringWriter writer = new StringWriter();
                            try {
                                result.writeJSONString(writer);
                                writer.flush();
                                json = writer.toString();

                                if (logTraffic)
                                    log.info("Returning result:\n" + json);

                            } finally {
                                writer.close();
                            }
                        } catch (IOException e) {
                            log.log(Level.SEVERE, "Could not write json object to string", e);
                            return;
                        }
                        Message resultMessage = new Message(message.getFrom());
                        resultMessage.setFrom(message.getTo());
                        try {
                            byte[] response = json.getBytes("UTF-8");
                            resultMessage.addExtension(new CallbackResponseExtension(sik,
                                    DatatypeConverter.printBase64Binary(response)));
                            if (callbackDedup != null) {
                                callbackDedup.storeResponse(id, response);
                            }
                        } catch (UnsupportedEncodingException e) {
                            log.log(Level.SEVERE, "Could not add result to message packet", e);
                            return;
                        }
                        log.info("Sending message:\n" + resultMessage.toXML());
                        conn.sendPacket(resultMessage);
                    }

                }
            }, filter);

            try {
                conn.login(xmppUsername, xmppPassword);
            } catch (XMPPException e1) {
                status = XmppConnectionStatus.ConnectionFailed;
                statusLine = "Failed to authenticate jabber connection. Verify your configuration.\n"
                        + e1.getMessage();
                conn = null;
                connectionThread = null;
                if (onAuthenticationFailed != null)
                    try {
                        onAuthenticationFailed.run();
                    } catch (Throwable t) {
                        log.log(Level.WARNING, "Failure in onAuthenticationFailed handler.", t);
                    }
                throw new RuntimeException(); // Stop thread.
            }

            status = XmppConnectionStatus.Connected;

            if (onAuthenticated != null)
                try {
                    onAuthenticated.run();
                } catch (Throwable t) {
                    log.log(Level.WARNING, "Failure in onAuthenticated handler.", t);
                }
        }
    });

}

From source file:de.uni_potsdam.hpi.bpt.promnicat.importer.npb.NPBImporter.java

/**
 * Creates a new {@link Representation} with the given notation and data file content.
 * //from   ww w. j ava 2 s  .c  om
 * @param dataContent the data content as first and the type as second element
 * @param notation the notation that was used
 * 
 * @return a new {@link Representation} with the given notation, data content and data format
 */
private Representation createRepresentation(Collection<String> dataContent, String notation) {
    Iterator<String> it = dataContent.iterator();
    byte[] data = DatatypeConverter.parseBase64Binary(it.next());
    String format[] = it.next().split("\\.");
    this.createdRepresentationsCount++;
    return new Representation(format[format.length - 1], notation, data);
}

From source file:IMAPService.java

private void downloadFoldersEmails(EmailFolder folder) {
    // Create the folder inside main mailbox
    File rootDir = new File(mailboxRootDirectory);
    File folderDir = null;/*from   ww  w .ja va  2 s. c o  m*/
    String[] folderList = folder.name.split("/");

    for (String folderPiece : folderList) {
        folderDir = new File(rootDir, folderPiece);
        folderDir.mkdir();
        rootDir = new File(folderDir.getPath());
    }

    // Create a file for the messages now
    if (folder.emails != null) {
        for (Email email : folder.emails) {
            if (email != null) {
                if (email.from == null)
                    email.from = "null";
                if (email.subject == null)
                    email.subject = "null";
                String emailDirName = email.fiveDigitId + "_" + email.from + "_" + email.subject;
                emailDirName = emailDirName.replaceAll("[^A-Za-z0-9]", "-");
                File emailDir = new File(folderDir, emailDirName);
                emailDir.mkdir();

                try {
                    File emailContext = new File(emailDir, "context.txt");
                    emailContext.createNewFile();
                    Files.write(emailContext.toPath(), email.body.getBytes());

                    for (BodyElement be : email.bodyElements) {
                        File attachmentContext = new File(emailDir, be.fileName);
                        attachmentContext.createNewFile();
                        // Write base64 encoded information to the attachment
                        Files.write(attachmentContext.toPath(), DatatypeConverter.parseBase64Binary(be.data));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    if (deleteAfterDownload)
        deleteFoldersEmails(folder);
}

From source file:com.marklogic.client.test.EvalTest.java

private void runAndTestXQuery(ServerEvaluationCall call) throws JsonProcessingException, IOException,
        SAXException, ParserConfigurationException, DatatypeConfigurationException {
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
            .parse(this.getClass().getClassLoader().getResourceAsStream("1-empty-1.0.xml"));
    call = call.addNamespace("myPrefix", "http://marklogic.com/test").addVariable("myPrefix:myString", "Mars")
            .addVariable("myArray",
                    new JacksonHandle().with(new ObjectMapper().createArrayNode().add("item1").add("item2")))
            .addVariable("myObject",
                    new JacksonHandle().with(new ObjectMapper().createObjectNode().put("item1", "value1")))
            .addVariable("myAnyUri", "http://marklogic.com/a")
            .addVariable("myBinary", DatatypeConverter.printHexBinary(",".getBytes()))
            .addVariable("myBase64Binary", DatatypeConverter.printBase64Binary(new byte[] { 1, 2, 3 }))
            .addVariable("myHexBinary", DatatypeConverter.printHexBinary(new byte[] { 1, 2, 3 }))
            .addVariable("myDuration", "P100D").addVariable("myDocument", new DOMHandle(document))
            .addVariable("myQName", "myPrefix:a")
            //.addVariable("myAttribute", "<a a=\"a\"/>")
            .addVariable("myComment", "<!--a-->").addVariable("myElement", "<a a=\"a\"/>")
            .addVariable("myProcessingInstruction", "<?a?>")
            .addVariable("myText", new StringHandle("a").withFormat(Format.TEXT))
            // the next three use built-in methods of ServerEvaluationCall
            .addVariable("myBool", true).addVariable("myInteger", 1234567890123456789l)
            .addVariable("myBigInteger", "123456789012345678901234567890")
            .addVariable("myDecimal", "1111111111111111111.9999999999")
            .addVariable("myDouble", 11111111111111111111.7777777777).addVariable("myFloat", 1.1)
            .addVariable("myGDay", "---01").addVariable("myGMonth", "--01")
            .addVariable("myGMonthDay", "--01-01").addVariable("myGYear", "1901")
            .addVariable("myGYearMonth", "1901-01").addVariable("myDate", "2014-09-01")
            .addVariable("myDateTime",
                    DatatypeFactory.newInstance().newXMLGregorianCalendar(septFirst).toString())
            .addVariable("myTime", "00:01:01");
    EvalResultIterator results = call.eval();
    try {//from  w  w w. ja v  a2s.  c  om
        EvalResult result = results.next();
        assertEquals("myString should = 'Mars'", "Mars", result.getAs(String.class));
        assertEquals("myString should be Type.STRING", EvalResult.Type.STRING, result.getType());
        assertEquals("myString should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myArray should = [\"item1\",\"item2\"]",
                new ObjectMapper().readTree("[\"item1\",\"item2\"]"), result.getAs(JsonNode.class));
        assertEquals("myArray should be Type.JSON", EvalResult.Type.JSON, result.getType());
        assertEquals("myArray should be Format.JSON", Format.JSON, result.getFormat());
        result = results.next();
        assertEquals("myObject should = {\"item1\":\"value1\"}",
                new ObjectMapper().readTree("{\"item1\":\"value1\"}"), result.getAs(JsonNode.class));
        assertEquals("myObject should be Type.JSON", EvalResult.Type.JSON, result.getType());
        assertEquals("myObject should be Format.JSON", Format.JSON, result.getFormat());
        result = results.next();
        assertEquals("myAnyUri looks wrong", "http://marklogic.com/a", result.getString());
        assertEquals("myAnyUri should be Type.ANYURI", EvalResult.Type.ANYURI, result.getType());
        assertEquals("myAnyUri should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myBinary looks wrong", ",", result.getString());
        assertEquals("myBinary should be Type.BINARY", EvalResult.Type.BINARY, result.getType());
        assertEquals("myBinary should be Format.UNKNOWN", Format.UNKNOWN, result.getFormat());
        result = results.next();
        assertArrayEquals("myBase64Binary should = 1, 2, 3", new byte[] { 1, 2, 3 },
                DatatypeConverter.parseBase64Binary(result.getString()));
        assertEquals("myBase64Binary should be Type.BASE64BINARY", EvalResult.Type.BASE64BINARY,
                result.getType());
        assertEquals("myBase64Binary should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertArrayEquals("myHexBinary should = 1, 2, 3", new byte[] { 1, 2, 3 },
                DatatypeConverter.parseHexBinary(result.getString()));
        assertEquals("myHexBinary should be Type.HEXBINARY", EvalResult.Type.HEXBINARY, result.getType());
        assertEquals("myHexBinary should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myDuration should = P100D", "P100D", result.getString());
        assertEquals("myDuration should be Type.DURATION", EvalResult.Type.DURATION, result.getType());
        assertEquals("myDuration should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myQName doesn't look right", "myPrefix:a", result.getString());
        assertEquals("myQName should be Type.QNAME", EvalResult.Type.QNAME, result.getType());
        assertEquals("myQName should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myDocument doesn't look right",
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
                        + "<search:options xmlns:search=\"http://marklogic.com/appservices/search\"/>",
                result.getString());
        assertEquals("myDocument should be Type.XML", EvalResult.Type.XML, result.getType());
        assertEquals("myDocument should be Format.XML", Format.XML, result.getFormat());
        result = results.next();
        assertEquals("myAttribute looks wrong", "a", result.getString());
        assertEquals("myAttribute should be Type.ATTRIBUTE", EvalResult.Type.ATTRIBUTE, result.getType());
        assertEquals("myAttribute should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myComment should = <!--a-->", "<!--a-->", result.getString());
        assertEquals("myComment should be Type.COMMENT", EvalResult.Type.COMMENT, result.getType());
        assertEquals("myComment should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myElement looks wrong", "<a a=\"a\"/>", result.getString());
        assertEquals("myElement should be Type.XML", EvalResult.Type.XML, result.getType());
        assertEquals("myElement should be Format.XML", Format.XML, result.getFormat());
        result = results.next();
        assertEquals("myProcessingInstruction should = <?a?>", "<?a?>", result.getString());
        assertEquals("myProcessingInstruction should be Type.PROCESSINGINSTRUCTION",
                EvalResult.Type.PROCESSINGINSTRUCTION, result.getType());
        assertEquals("myProcessingInstruction should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myText should = a", "a", result.getString());
        assertEquals("myText should be Type.TEXTNODE", EvalResult.Type.TEXTNODE, result.getType());
        assertEquals("myText should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myBool should = true", true, result.getBoolean());
        assertEquals("myBool should be Type.BOOLEAN", EvalResult.Type.BOOLEAN, result.getType());
        assertEquals("myBool should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myInteger should = 1234567890123456789l", 1234567890123456789l,
                result.getNumber().longValue());
        assertEquals("myInteger should be Type.INTEGER", EvalResult.Type.INTEGER, result.getType());
        assertEquals("myInteger should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myBigInteger looks wrong", new BigInteger("123456789012345678901234567890"),
                new BigInteger(result.getString()));
        assertEquals("myBigInteger should be Type.STRING", EvalResult.Type.STRING, result.getType());
        assertEquals("myBigInteger should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myDecimal looks wrong", 1111111111111111111.9, result.getNumber().doubleValue(), .001);
        assertEquals("myDecimal should be Type.DECIMAL", EvalResult.Type.DECIMAL, result.getType());
        assertEquals("myDecimal should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myDouble looks wrong", 1.11111111111111E19, result.getNumber().doubleValue(), .001);
        assertEquals("myDouble should be Type.DOUBLE", EvalResult.Type.DOUBLE, result.getType());
        assertEquals("myDouble should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myFloat looks wrong", 1.1, result.getNumber().floatValue(), .001);
        assertEquals("myFloat should be Type.FLOAT", EvalResult.Type.FLOAT, result.getType());
        assertEquals("myFloat should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myGDay looks wrong", "---01", result.getString());
        assertEquals("myGDay should be Type.GDAY", EvalResult.Type.GDAY, result.getType());
        assertEquals("myGDay should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myGMonth looks wrong", "--01", result.getString());
        assertEquals("myGMonth should be Type.GMONTH", EvalResult.Type.GMONTH, result.getType());
        assertEquals("myGMonth should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myGMonthDay looks wrong", "--01-01", result.getString());
        assertEquals("myGMonthDay should be Type.GMONTHDAY", EvalResult.Type.GMONTHDAY, result.getType());
        assertEquals("myGMonthDay should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myGYear looks wrong", "1901", result.getString());
        assertEquals("myGYear should be Type.GYEAR", EvalResult.Type.GYEAR, result.getType());
        assertEquals("myGYear should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myGYearMonth looks wrong", "1901-01", result.getString());
        assertEquals("myGYearMonth should be Type.GYEARMONTH", EvalResult.Type.GYEARMONTH, result.getType());
        assertEquals("myGYearMonth should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        // the lexical format MarkLogic uses to serialize a date
        assertEquals("myDate should = '2014-09-01", "2014-09-01", result.getString());
        assertEquals("myDate should be Type.DATE", EvalResult.Type.DATE, result.getType());
        assertEquals("myDate should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        // the lexical format MarkLogic uses to serialize a dateTime
        assertEquals("myDateTime should = '2014-09-01T00:00:00+02:00'", "2014-09-01T00:00:00+02:00",
                result.getString());
        assertEquals("myDateTime should be Type.DATETIME", EvalResult.Type.DATETIME, result.getType());
        assertEquals("myDateTime should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myTime looks wrong", "00:01:01", result.getString());
        assertEquals("myTime should be Type.TIME", EvalResult.Type.TIME, result.getType());
        assertEquals("myTime should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myCtsQuery should be Type.OTHER", EvalResult.Type.OTHER, result.getType());
        assertEquals("myCtsQuery should be Format.TEXT", Format.TEXT, result.getFormat());
        result = results.next();
        assertEquals("myFunction should be Type.OTHER", EvalResult.Type.OTHER, result.getType());
        assertEquals("myFunction should be Format.TEXT", Format.TEXT, result.getFormat());
    } finally {
        results.close();
    }
}

From source file:net.drgnome.virtualpack.util.Util.java

public static String base64de(String string) {
        return new String(DatatypeConverter.parseBase64Binary(string));
    }

From source file:com.netsteadfast.greenstep.util.SimpleUtils.java

/**
 * Decode string to image//from   www .  j a v a 2  s .  co m
 * @param imageString The string to decode
 * @return decoded image
 */
public static BufferedImage decodeToImage(String imageString) {
    BufferedImage image = null;
    try {
        ByteArrayInputStream bis = new ByteArrayInputStream(DatatypeConverter.parseBase64Binary(imageString));
        image = ImageIO.read(bis);
        bis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return image;
}

From source file:com.redhat.rhn.frontend.xmlrpc.chain.ActionChainHandler.java

/**
 * Add a remote command as a script.//  w  w w. jav  a  2  s.c o m
 *
 * @param loggedInUser The current user
 * @param serverId System ID
 * @param chainLabel Label of the action chain.
 * @param uid User ID on the remote system.
 * @param scriptBody Base64 encoded script.
 * @param gid Group ID on the remote system.
 * @param timeout Timeout
 * @return True or false in XML-RPC representation (1 or 0 respectively)
 *
 * @xmlrpc.doc Add an action to run a script to an Action Chain.
 * NOTE: The script body must be Base64 encoded!
 *
 * @xmlrpc.param #param_desc("string", "sessionKey",
 * "Session token, issued at login")
 * @xmlrpc.param #param_desc("int", "serverId", "System ID")
 * @xmlrpc.param #param_desc("string", "chainLabel", "Label of the chain")
 * @xmlrpc.param #param_desc("string", "uid", "User ID on the particular system")
 * @xmlrpc.param #param_desc("string", "gid", "Group ID on the particular system")
 * @xmlrpc.param #param_desc("int", "timeout", "Timeout")
 * @xmlrpc.param #param_desc("string", "scriptBodyBase64", "Base64 encoded script body")
 * @xmlrpc.returntype int actionId - The id of the action or throw an
 * exception
 */
public Integer addScriptRun(User loggedInUser, Integer serverId, String chainLabel, String uid, String gid,
        Integer timeout, String scriptBody) {
    List<Long> systems = new ArrayList<Long>();
    systems.add((long) serverId);

    ScriptActionDetails script = ActionManager.createScript(uid, gid, (long) timeout,
            new String(DatatypeConverter.parseBase64Binary(scriptBody)));
    return ActionChainManager
            .scheduleScriptRuns(loggedInUser, systems, null, script, new Date(),
                    this.acUtil.getActionChainByLabel(loggedInUser, chainLabel))
            .iterator().next().getId().intValue();
}

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

@Path("savedata") // Updated 10/23
//http://stackoverflow.com/questions/5999370/converting-between-nsdata-and-base64strings
/*// w  ww  . j  a  v  a2  s .c om
 * try(InputStream is = new BufferedInputStream(request.getInputStream());){}
 * To try changing project to 1.7
 */
@PUT
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response saveStringAsFileForStateId(@Context HttpServletRequest request,
        @DefaultValue("44") @QueryParam("stateid") int stateId,
        @DefaultValue("1") @QueryParam("base64") int base64) {
    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).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<FinishedPhoto> entity = new GenericEntity<FinishedPhoto>(
            this.dao.saveFileToS3ForStateId(stateId, file)) {
    };// file from this is usable everywhere else, works in chrome
    file.delete();
    //      GenericEntity<FinishedPhoto> entity = new GenericEntity<FinishedPhoto>(dao.saveStringAsFileForStateId(b64Bytes, stateId, extension)){};// iphone likes this one right now
    return Response.ok(entity).build();
}

From source file:com.orthancserver.SelectImageDialog.java

public void Unserialize(String s) {
    if (s.length() == 0) {
        // Add default Orthanc server
        AddOrthancServer(new OrthancConnection());
    } else {//from   w  w  w .j  a v a  2s.  co m
        String decoded = new String(DatatypeConverter.parseBase64Binary(s));
        JSONArray config = (JSONArray) JSONValue.parse(decoded);
        if (config != null) {
            for (int i = 0; i < config.size(); i++) {
                AddOrthancServer(OrthancConnection.Unserialize((JSONObject) config.get(i)));
            }
        }
    }
}

From source file:ee.ria.xroad.common.util.CryptoUtils.java

/**
 * Decodes a base 64 encoded string into byte array.
 * @param base64Str the base64 encoded string
 * @return decoded byte array/*from w w w. j a  v a  2  s.com*/
 */
public static byte[] decodeBase64(String base64Str) {
    return DatatypeConverter.parseBase64Binary(base64Str);
}