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

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

Introduction

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

Prototype

public Base64() 

Source Link

Document

Creates a Base64 codec used for decoding (all modes) and encoding in URL-unsafe mode.

Usage

From source file:UploadTest.java

@Test
public void form_test() {
    try {/*from   w w w  .  ja v  a 2s .c  o m*/
        url = new URL("http://localhost:9000/resource/frl:6376982/data");
        httpCon = (HttpURLConnection) url.openConnection();
        String userpass = user + ":" + password;
        basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
        httpCon.setRequestProperty("Authorization", basicAuth);
        String fieldName = "data";
        File uploadFile = new File("/home/raul/test/frl%3A6376982/6376990.pdf");
        String boundary = "" + System.currentTimeMillis() + "";

        httpCon.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        httpCon.setRequestProperty("file", "6376986.pdf");

        httpCon.setUseCaches(false);
        httpCon.setDoOutput(true);
        httpCon.setDoInput(true);

        httpCon.setRequestMethod("PUT");

        OutputStream outputStream = null;
        try {
            outputStream = (httpCon.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String LINE_FEED = "\r\n";
        String fileName = uploadFile.getName();
        writer.append("--" + boundary).append(LINE_FEED);
        System.out.println("--" + boundary + (LINE_FEED));
        writer.append(
                "Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"")
                .append(LINE_FEED);
        System.out.println("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName
                + "\"" + (LINE_FEED));
        writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
        System.out.println("Content-Type: " + URLConnection.guessContentTypeFromName(fileName) + (LINE_FEED));
        writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
        System.out.println("Content-Transfer-Encoding: binary" + (LINE_FEED));
        writer.append(LINE_FEED);

        writer.flush();

        fileToOutputStream(uploadFile, outputStream);

        // httpCon.getInputStream();
        try {
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

        writer.append(LINE_FEED);
        writer.flush();
        writer.close();
        httpCon.disconnect();

        try {
            System.out.println(httpCon.getResponseCode());
            System.out.println(httpCon.getResponseMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:de.zib.gndms.kit.monitor.GroovyMoniServlet.java

private static String parseAction(HttpServletRequestWrapper requestWrapper) {
    final String monitorArgs = requestWrapper.getParameter("action");
    final Base64 b64 = new Base64();
    return monitorArgs == null ? "" : new String(b64.decode(monitorArgs));
}

From source file:de.zib.gndms.kit.monitor.GroovyMoniServlet.java

private static String parseArgs(HttpServletRequestWrapper requestWrapper) {
    final String monitorArgs = requestWrapper.getParameter("args");
    final Base64 b64 = new Base64();
    return monitorArgs == null ? "" : new String(b64.decode(monitorArgs));
}

From source file:it.govpay.core.utils.client.BasicClient.java

private byte[] send(boolean soap, String azione, JAXBElement<?> body, Object header, boolean isAzioneInUrl)
        throws ClientException {

    // Creazione Connessione
    int responseCode;
    HttpURLConnection connection = null;
    byte[] msg = null;
    GpContext ctx = GpThreadLocal.get();
    String urlString = url.toExternalForm();
    if (isAzioneInUrl) {
        if (!urlString.endsWith("/"))
            urlString = urlString.concat("/");
        try {// w  w w.  ja va2 s.com
            url = new URL(urlString.concat(azione));
        } catch (MalformedURLException e) {
            throw new ClientException("Url di connessione malformata: " + urlString.concat(azione), e);
        }
    }

    try {
        Message requestMsg = new Message();
        requestMsg.setType(MessageType.REQUEST_OUT);

        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        if (soap) {
            connection.setRequestProperty("SOAPAction", "\"" + azione + "\"");
            requestMsg.addHeader(new Property("SOAPAction", "\"" + azione + "\""));
        }
        requestMsg.setContentType("text/xml");
        connection.setRequestProperty("Content-Type", "text/xml");
        connection.setRequestMethod("POST");

        // Imposta Contesto SSL se attivo
        if (sslContext != null) {
            HttpsURLConnection httpsConn = (HttpsURLConnection) connection;
            httpsConn.setSSLSocketFactory(sslContext.getSocketFactory());
            HostNameVerifierDisabled disabilitato = new HostNameVerifierDisabled();
            httpsConn.setHostnameVerifier(disabilitato);
        }

        // Imposta l'autenticazione HTTP Basic se attiva
        if (ishttpBasicEnabled) {
            Base64 base = new Base64();
            String encoding = new String(base.encode((httpBasicUser + ":" + httpBasicPassword).getBytes()));
            connection.setRequestProperty("Authorization", "Basic " + encoding);
            requestMsg.addHeader(new Property("Authorization", "Basic " + encoding));
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        if (soap) {
            SOAPUtils.writeMessage(body, header, baos);
        } else {
            JaxbUtils.marshal(body, baos);
        }

        ctx.getIntegrationCtx().setMsg(baos.toByteArray());
        invokeOutHandlers();

        if (log.getLevel().isMoreSpecificThan(Level.TRACE)) {
            StringBuffer sb = new StringBuffer();
            for (String key : connection.getRequestProperties().keySet()) {
                sb.append("\n\t" + key + ": " + connection.getRequestProperties().get(key));
            }
            sb.append("\n" + new String(ctx.getIntegrationCtx().getMsg()));
            log.trace(sb.toString());
        }

        requestMsg.setContent(ctx.getIntegrationCtx().getMsg());

        ctx.getContext().getRequest().setOutDate(new Date());
        ctx.getContext().getRequest().setOutSize(Long.valueOf(ctx.getIntegrationCtx().getMsg().length));
        ctx.log(requestMsg);

        connection.getOutputStream().write(ctx.getIntegrationCtx().getMsg());

    } catch (Exception e) {
        throw new ClientException(e);
    }
    try {
        responseCode = connection.getResponseCode();
        ctx.getTransaction().getServer().setTransportCode(Integer.toString(responseCode));

    } catch (Exception e) {
        throw new ClientException(e);
    }

    Message responseMsg = new Message();
    responseMsg.setType(MessageType.RESPONSE_IN);

    for (String key : connection.getHeaderFields().keySet()) {
        if (connection.getHeaderFields().get(key) != null) {
            if (key == null)
                responseMsg
                        .addHeader(new Property("Status-line", connection.getHeaderFields().get(key).get(0)));
            else if (connection.getHeaderFields().get(key).size() == 1)
                responseMsg.addHeader(new Property(key, connection.getHeaderFields().get(key).get(0)));
            else
                responseMsg.addHeader(
                        new Property(key, ArrayUtils.toString(connection.getHeaderFields().get(key))));
        }
    }

    try {
        if (responseCode < 300) {
            try {
                if (connection.getInputStream() == null) {
                    return null;
                }
                msg = connection.getInputStream() != null ? IOUtils.toByteArray(connection.getInputStream())
                        : new byte[] {};
                if (msg.length > 0)
                    responseMsg.setContent(msg);
                return msg;
            } catch (Exception e) {
                throw new ClientException("Messaggio di risposta non valido", e);
            }
        } else {
            try {
                msg = connection.getErrorStream() != null ? IOUtils.toByteArray(connection.getErrorStream())
                        : new byte[] {};
                responseMsg.setContent(msg);
            } catch (IOException e) {
                msg = ("Impossibile serializzare l'ErrorStream della risposta: " + e).getBytes();
            } finally {
                log.warn("Errore nell'invocazione del Nodo dei Pagamenti [HTTP Response Code " + responseCode
                        + "]\nRisposta: " + new String(msg));
            }

            throw new ClientException("Ricevuto [HTTP " + responseCode + "]");
        }
    } finally {
        if (responseMsg != null) {
            ctx.getContext().getResponse().setInDate(new Date());
            ctx.getContext().getResponse().setInSize((long) responseMsg.getContent().length);
            ctx.log(responseMsg);
        }

        if (log.getLevel().isMoreSpecificThan(Level.TRACE) && connection != null
                && connection.getHeaderFields() != null) {
            StringBuffer sb = new StringBuffer();
            for (String key : connection.getHeaderFields().keySet()) {
                sb.append("\n\t" + key + ": " + connection.getHeaderField(key));
            }
            sb.append("\n" + new String(msg));
            log.trace(sb.toString());
        }
    }

}

From source file:com.xebialabs.overthere.cifs.winrm.WinRmClient.java

private static void handleStream(Document responseDocument, ResponseExtractor stream, OutputStream out)
        throws IOException {
    @SuppressWarnings("unchecked")
    final List<Element> streams = stream.getXPath().selectNodes(responseDocument);
    if (!streams.isEmpty()) {
        final Base64 base64 = new Base64();
        Iterator<Element> itStreams = streams.iterator();
        while (itStreams.hasNext()) {
            Element e = itStreams.next();
            // TODO check performance with http://www.iharder.net/current/java/base64/
            final byte[] decode = base64.decode(e.getText());
            out.write(decode);/*w w  w . java  2 s . c om*/
        }
    }

}

From source file:gov.tva.sparky.util.indexer.HistorianArchiveLookupTableEntry.java

public static String EncodeKeyAsBase64String(String strInKey) {

    String strOutKey = "";

    Base64 base64 = new Base64();

    byte[] encoded_bytes = base64.encode(strInKey.getBytes());

    strOutKey = new String(encoded_bytes);

    return strOutKey;

}

From source file:fi.hoski.web.forms.RaceEntryServlet.java

/**
 * Handles the HTTP//from w w w. j  a v  a2 s  .  co m
 * <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        String raceFleetKeyStr = request.getParameter("RaceFleetKey");
        if (raceFleetKeyStr == null) {
            throw new ServletException("no RaceFleetKey");
        }
        Key raceFleetKey = KeyFactory.stringToKey(raceFleetKeyStr);
        Entity raceFleetEntity = datastore.get(raceFleetKey);
        Key raceSeriesKey = raceFleetKey.getParent();
        Entity raceseriesEntity = datastore.get(raceSeriesKey);
        RaceSeries raceSeries = (RaceSeries) entities.newInstance(raceseriesEntity);
        RaceFleet raceFleet = (RaceFleet) entities.newInstance(raceFleetEntity);
        RaceEntry raceEntry = new RaceEntry(raceFleet);
        raceEntry.populate(request.getParameterMap());

        String fn = request.getParameter(RaceEntry.FIRSTNAME);
        String ln = request.getParameter(RaceEntry.LASTNAME);
        raceEntry.set(RaceEntry.HELMNAME, fn + " " + ln);

        String sa = request.getParameter(RaceEntry.STREETADDRESS);
        String zc = request.getParameter(RaceEntry.ZIPCODE);
        String ct = request.getParameter(RaceEntry.CITY);
        String cn = request.getParameter(RaceEntry.COUNTRY);
        if (cn == null || cn.isEmpty()) {
            raceEntry.set(RaceEntry.HELMADDRESS, sa + ", " + zc + " " + ct);
        } else {
            raceEntry.set(RaceEntry.HELMADDRESS, sa + ", " + zc + " " + ct + ", " + cn);
        }

        Day closingDay = (Day) raceSeries.get(RaceSeries.ClosingDate);
        Number fee = 0.0;
        if (closingDay != null) {
            Day now = new Day();
            if (closingDay.before(now)) {
                fee = (Number) raceFleet.get(RaceFleet.Fee2);
            } else {
                fee = (Number) raceFleet.get(RaceFleet.Fee);
            }
        }
        Boolean clubDiscount = (Boolean) raceSeries.get(RaceSeries.CLUBDISCOUNT);
        String clubname = repositoryBundle.getString("Clubname");
        if (clubDiscount != null && clubDiscount
                && clubname.equalsIgnoreCase("" + raceEntry.get(RaceEntry.CLUB))) {
            fee = new Double(0);
        }
        raceEntry.set(RaceEntry.FEE, fee);
        raceEntry.set(RaceEntry.TIMESTAMP, new Date());

        entities.put(raceEntry);

        String payingInstructions = "";
        String payingInstructionsHtml = "";
        BankingBarcode bb = races.getBarcode(raceEntry);
        if (bb != null) {
            Day dueDay = new Day(bb.getDueDate());
            String payingFormat = EntityReferences.encode(msg(Messages.RACEENTRYPAYING), "UTF-8");
            String bic = EntityReferences.encode(msg(Messages.RACEBIC), "UTF-8");
            payingInstructions = String.format(payingFormat, bb.toString(), // 1 = barcode
                    bb.getAccount().getIBAN(), // 2 = account
                    bb.getReference().toFormattedRFString(), // 3 = ref
                    dueDay, // 4 = due date
                    String.format("%.2f", bb.getTotal()), // 5 = total
                    bic // 6 = bic
            );
            payingInstructionsHtml = String.format(payingFormat.replace("\n", "<br>"),
                    "<span id='barcode'>" + bb.toString() + "</span>", // 1 = barcode
                    "<span id='iban'>" + bb.getAccount().getIBAN() + "</span>", // 2 = account
                    "<span id='rf'>" + bb.getReference().toFormattedRFString() + "</span>", // 3 = ref
                    "<span id='due'>" + dueDay + "</span>", // 4 = due date
                    "<span id='fee'>" + String.format("%.2f", bb.getTotal()) + "</span>", // 5 = total
                    "<span id='bic'>" + bic + "</span>" // 6 = bic
            );
        }
        URL base = new URL(request.getRequestURL().toString());
        URL barcodeUrl = new URL(base, "/races/code128.html?ancestor=" + raceEntry.createKeyString());
        String name = (String) raceEntry.get(RaceEntry.HELMNAME);
        String email = (String) raceEntry.get(RaceEntry.HELMEMAIL);
        String confirmation = msg(Messages.RACEENTRYCONFIRMATION);
        String plainMessage = "";
        String htmlMessage = "<html><head></head><body>" + EntityReferences.encode(confirmation)
                + payingInstructionsHtml + raceEntry.getFieldsAsHtmlTable() + "<iframe src="
                + barcodeUrl.toString() + "/>" + "</body></html>";
        if (email != null) {
            InternetAddress recipient = new InternetAddress(email, name);
            String senderStr = msg(Messages.RACEENTRYFROMADDRESS);
            InternetAddress sender;
            try {
                sender = new InternetAddress(senderStr);
                plainMessage = confirmation + "\n" + payingInstructions + "\n" + raceEntry.getFields();

                String subject = msg(Messages.RACEENTRYSUBJECT);
                mailService.sendMail(sender, subject, plainMessage, htmlMessage, recipient);
            } catch (Exception ex) {
                log(senderStr, ex);
            }
        }
        Cookie cookie = null;
        Cookie[] cookies = null;
        if (useCookies) {
            cookies = request.getCookies();
        }
        if (cookies != null) {
            for (Cookie ck : cookies) {
                if (COOKIENAME.equals(ck.getName())) {
                    cookie = ck;
                }
            }
        }
        JSONObject json = null;
        if (useCookies && cookie != null) {
            Base64 decoder = new Base64();
            String str = new String(decoder.decode(cookie.getValue()));
            json = new JSONObject(str);
        } else {
            json = new JSONObject();
        }
        for (Map.Entry<String, String[]> entry : ((Map<String, String[]>) request.getParameterMap())
                .entrySet()) {
            String property = entry.getKey();
            String[] values = entry.getValue();
            if (values.length == 1) {
                json.put(property, values[0]);
            }
        }
        Base64 encoder = new Base64();
        String base64 = encoder.encodeAsString(json.toString().getBytes("UTF-8"));
        if (useCookies) {
            if (cookie == null) {
                cookie = new Cookie(COOKIENAME, base64);
                cookie.setPath("/");
                cookie.setMaxAge(400 * 24 * 60 * 60);
            } else {
                cookie.setValue(base64);
            }
            response.addCookie(cookie);
        }
        sendError(response, HttpServletResponse.SC_OK,
                "<div id=\"" + raceEntry.createKeyString() + "\">Ok</div>");
    } catch (JSONException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "<div id=\"eJSON\">Internal error.</div>");
    } catch (EntityNotFoundException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "<div id=\"eEntityNotFound\">Internal error.</div>");
    } catch (NumberFormatException ex) {
        log(ex.getMessage(), ex);
        sendError(response, HttpServletResponse.SC_CONFLICT, "<div id=\"eNumberFormat\">Number error.</div>");
    }
}

From source file:fi.aalto.seqpig.io.BamStorer.java

@Override
public void checkSchema(ResourceSchema s) throws IOException {

    selectedBAMAttributes = new HashMap<String, Integer>();
    allBAMFieldNames = new HashMap<String, Integer>();
    String[] fieldNames = s.fieldNames();

    for (int i = 0; i < fieldNames.length; i++) {
        System.out.println("field: " + fieldNames[i]);
        allBAMFieldNames.put(fieldNames[i], new Integer(i));

        if (fieldNames[i].equalsIgnoreCase("RG") || fieldNames[i].equalsIgnoreCase("LB")
                || fieldNames[i].equalsIgnoreCase("PU") || fieldNames[i].equalsIgnoreCase("PG")
                || fieldNames[i].equalsIgnoreCase("AS") || fieldNames[i].equalsIgnoreCase("SQ")
                || fieldNames[i].equalsIgnoreCase("MQ") || fieldNames[i].equalsIgnoreCase("NM")
                || fieldNames[i].equalsIgnoreCase("H0") || fieldNames[i].equalsIgnoreCase("H1")
                || fieldNames[i].equalsIgnoreCase("H2") || fieldNames[i].equalsIgnoreCase("UQ")
                || fieldNames[i].equalsIgnoreCase("PQ") || fieldNames[i].equalsIgnoreCase("NH")
                || fieldNames[i].equalsIgnoreCase("IH") || fieldNames[i].equalsIgnoreCase("HI")
                || fieldNames[i].equalsIgnoreCase("MD") || fieldNames[i].equalsIgnoreCase("CS")
                || fieldNames[i].equalsIgnoreCase("CQ") || fieldNames[i].equalsIgnoreCase("CM")
                || fieldNames[i].equalsIgnoreCase("R2") || fieldNames[i].equalsIgnoreCase("Q2")
                || fieldNames[i].equalsIgnoreCase("S2") || fieldNames[i].equalsIgnoreCase("CC")
                || fieldNames[i].equalsIgnoreCase("CP") || fieldNames[i].equalsIgnoreCase("SM")
                || fieldNames[i].equalsIgnoreCase("AM") || fieldNames[i].equalsIgnoreCase("MF")
                || fieldNames[i].equalsIgnoreCase("E2") || fieldNames[i].equalsIgnoreCase("U2")
                || fieldNames[i].equalsIgnoreCase("OQ")) {

            System.out.println("selected attribute: " + fieldNames[i] + " i: " + i);
            selectedBAMAttributes.put(fieldNames[i], new Integer(i));
        }/*from   ww w.  ja  v  a2s. c  o m*/
    }

    if (!(allBAMFieldNames.containsKey("name") && allBAMFieldNames.containsKey("start")
            && allBAMFieldNames.containsKey("end") && allBAMFieldNames.containsKey("read")
            && allBAMFieldNames.containsKey("cigar") && allBAMFieldNames.containsKey("basequal")
            && allBAMFieldNames.containsKey("flags") && allBAMFieldNames.containsKey("insertsize")
            && allBAMFieldNames.containsKey("mapqual") && allBAMFieldNames.containsKey("matestart")
            && allBAMFieldNames.containsKey("materefindex") && allBAMFieldNames.containsKey("refindex")))
        throw new IOException("Error: Incorrect BAM tuple-field name or compulsory field missing");

    Base64 codec = new Base64();
    Properties p = UDFContext.getUDFContext().getUDFProperties(this.getClass());
    String datastr;

    ByteArrayOutputStream bstream = new ByteArrayOutputStream();
    ObjectOutputStream ostream = new ObjectOutputStream(bstream);
    ostream.writeObject(selectedBAMAttributes);
    ostream.close();
    datastr = codec.encodeBase64String(bstream.toByteArray());
    p.setProperty("selectedBAMAttributes", datastr);

    bstream = new ByteArrayOutputStream();
    ostream = new ObjectOutputStream(bstream);
    ostream.writeObject(allBAMFieldNames);
    ostream.close();
    datastr = codec.encodeBase64String(bstream.toByteArray());
    p.setProperty("allBAMFieldNames", datastr);
}

From source file:gov.tva.sparky.util.indexer.HistorianArchiveLookupTableEntry.java

public static String DecodeKeyFromBase64String(String strInKey) {

    String strOutKey = "";

    Base64 base64 = new Base64();
    byte[] decoded_bytes = base64.decode(strInKey.getBytes());
    strOutKey = new String(decoded_bytes);
    return strOutKey;

}

From source file:femr.business.services.PhotoService.java

/**
 * Decodes a base64 encoded string to an image
 *
 * @param imageString base64 encoded string that has been parsed to only include imageBytes
 * @return the decoded image/* ww w . j a va 2  s  . c o m*/
 */
private static BufferedImage decodeToImage(String imageString) {

    BufferedImage image = null;
    byte[] imageByte;
    try {
        Base64 newDecoder = new Base64();
        byte[] bytes = imageString.getBytes(Charset.forName("UTF-8"));
        imageByte = newDecoder.decode(bytes);
        ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
        image = ImageIO.read(bis);
        bis.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return image;
}