Example usage for javax.xml.bind DatatypeConverter printBase64Binary

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

Introduction

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

Prototype

public static String printBase64Binary(byte[] val) 

Source Link

Document

Converts an array of bytes into a string.

Usage

From source file:fr.inria.oak.paxquery.translation.Logical2Pact.java

private static final Operator<Record>[] translate(Flatten flat) {
    Operator<Record>[] childPlan = translate(flat.getChild());

    // create MapOperator to flatten tuples
    MapOperator flatten = MapOperator.builder(FlattenOperator.class).input(childPlan).name("Flatten").build();

    // flatten configuration
    final String encodedFlattenNRSMD = DatatypeConverter
            .printBase64Binary(SerializationUtils.serialize(flat.getNRSMD()));
    flatten.setParameter(PACTOperatorsConfiguration.NRSMD1_BINARY.toString(), encodedFlattenNRSMD);
    final String encodedUnnestPath = DatatypeConverter
            .printBase64Binary(SerializationUtils.serialize(flat.getUnnestPath()));
    flatten.setParameter(PACTOperatorsConfiguration.UNNEST_PATH_BINARY.toString(), encodedUnnestPath);

    return new Operator[] { flatten };
}

From source file:org.cloudcoder.app.server.rpc.GetCoursesAndProblemsServiceImpl.java

@Override
public OperationResult submitExercise(ProblemAndTestCaseList exercise, String repoUsername, String repoPassword)
        throws CloudCoderAuthenticationException {
    logger.warn("Sharing exercise: " + exercise.getProblem().getTestname());

    // Only a course instructor may share an exercise.
    User authenticatedUser = ServletUtil.checkClientIsAuthenticated(getThreadLocalRequest(),
            GetCoursesAndProblemsServiceImpl.class);
    Course course = new Course();
    course.setId(exercise.getProblem().getCourseId());
    Database.getInstance().reloadModelObject(course);
    CourseRegistrationList regList = Database.getInstance().findCourseRegistrations(authenticatedUser, course);
    if (!regList.isInstructor()) {
        return new OperationResult(false, "You must be an instructor to share an exercise");
    }//from ww  w.  jav a 2 s. c  o m

    // Get the exercise repository URL
    ConfigurationSetting repoUrlSetting = Database.getInstance()
            .getConfigurationSetting(ConfigurationSettingName.PUB_REPOSITORY_URL);
    if (repoUrlSetting == null) {
        return new OperationResult(false, "URL of exercise repository is not configured");
    }
    String repoUrl = repoUrlSetting.getValue();
    if (repoUrl.endsWith("/")) {
        repoUrl = repoUrl.substring(0, repoUrl.length() - 1);
    }

    HttpPost post = new HttpPost(repoUrl + "/exercisedata");

    // Encode an Authorization header using the provided repository username and password.
    String authHeaderValue = "Basic " + DatatypeConverter
            .printBase64Binary((repoUsername + ":" + repoPassword).getBytes(Charset.forName("UTF-8")));
    //System.out.println("Authorization: " + authHeaderValue);
    post.addHeader("Authorization", authHeaderValue);

    // Convert the exercise to a JSON string
    StringEntity entity;
    StringWriter sw = new StringWriter();
    try {
        JSONConversion.writeProblemAndTestCaseData(exercise, sw);
        entity = new StringEntity(sw.toString(), ContentType.create("application/json", "UTF-8"));
    } catch (IOException e) {
        return new OperationResult(false, "Could not convert exercise to JSON: " + e.getMessage());
    }
    post.setEntity(entity);

    // POST the exercise to the repository
    HttpClient client = new DefaultHttpClient();
    try {
        HttpResponse response = client.execute(post);

        StatusLine statusLine = response.getStatusLine();

        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            // Update the exercise's shared flag so we have a record that it was shared.
            exercise.getProblem().setShared(true);
            Database.getInstance().storeProblemAndTestCaseList(exercise, course, authenticatedUser);

            return new OperationResult(true, "Exercise successfully published to the repository - thank you!");
        } else if (statusLine.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            return new OperationResult(false,
                    "Authentication with repository failed - incorrect username/password?");
        } else {
            return new OperationResult(false,
                    "Failed to publish exercise to repository: " + statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        return new OperationResult(false, "Error sending exercise to repository: " + e.getMessage());
    } catch (IOException e) {
        return new OperationResult(false, "Error sending exercise to repository: " + e.getMessage());
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:fr.inria.oak.paxquery.translation.Logical2Pact.java

private static final Operator<Record>[] translate(GroupBy gb) {
    final boolean withAggregation = gb instanceof GroupByWithAggregation;

    Operator<Record>[] childPlan = translate(gb.getChild());

    // create ReduceOperator for grouping
    ReduceOperator.Builder groupByBuilder;
    if (withAggregation)
        groupByBuilder = ReduceOperator.builder(GroupByWithAggregationOperator.class).input(childPlan)
                .name("GroupByAgg");
    else// www .j a  v  a2 s .c  o m
        groupByBuilder = ReduceOperator.builder(GroupByOperator.class).input(childPlan).name("GroupBy");
    for (int column : gb.getReduceByColumns())
        KeyFactoryOperations.addKey(groupByBuilder,
                MetadataTypesMapping.getKeyClass(gb.getChild().getNRSMD().getType(column)), column);
    ReduceOperator groupBy = groupByBuilder.build();

    // groupBy configuration
    final String encodedNRSMD = DatatypeConverter
            .printBase64Binary(SerializationUtils.serialize(gb.getNRSMD()));
    groupBy.setParameter(PACTOperatorsConfiguration.NRSMD1_BINARY.toString(), encodedNRSMD);
    final String encodedGroupByColumns = DatatypeConverter
            .printBase64Binary(SerializationUtils.serialize((gb.getGroupByColumns())));
    groupBy.setParameter(PACTOperatorsConfiguration.GROUP_BY_COLUMNS_BINARY.toString(), encodedGroupByColumns);
    final String encodedNestColumns = DatatypeConverter
            .printBase64Binary(SerializationUtils.serialize((gb.getNestColumns())));
    groupBy.setParameter(PACTOperatorsConfiguration.NEST_COLUMNS_BINARY.toString(), encodedNestColumns);
    if (withAggregation) {
        GroupByWithAggregation gba = (GroupByWithAggregation) gb;

        groupBy.setParameter(PACTOperatorsConfiguration.AGGREGATION_COLUMN_INT.toString(),
                gba.getAggregationColumn());

        final String encodedAggregationType = DatatypeConverter
                .printBase64Binary(SerializationUtils.serialize(gba.getAggregationType()));
        groupBy.setParameter(PACTOperatorsConfiguration.AGGREGATION_TYPE_BINARY.toString(),
                encodedAggregationType);

        groupBy.setParameter(PACTOperatorsConfiguration.EXCLUDE_NESTED_FIELD_BOOLEAN.toString(),
                gba.isExcludeNestedField());
    }

    return new Operator[] { groupBy };
}

From source file:com.mobicage.rogerthat.xmpp.CallBackApiXMPPListener.java

/**
 * Establish an XMPP connection to XmppService and listen for Rogerthat API callbacks.
 *///from   w ww  .j av  a2 s .  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:com.ibm.devops.dra.PublishSQ.java

/**
 * Sends POST method to DLMS to upload SQ results
 *F//from   w w w.  j a v  a  2  s.  c o  m
 * @param bluemixToken the bluemix auth header that allows us to talk to dlms
 * @param payload the content part of the payload to send to dlms
 * @param urls a json array that holds the urls for a payload
 * @return boolean based on if the request was successful or not
 */
private boolean sendPayloadToDLMS(String bluemixToken, JsonObject payload, JsonArray urls) {
    String resStr = "";
    printStream.println("[IBM Cloud DevOps] Uploading SonarQube results...");
    try {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        HttpPost postMethod = new HttpPost(this.dlmsUrl);
        postMethod = addProxyInformation(postMethod);
        postMethod.setHeader("Authorization", bluemixToken);
        postMethod.setHeader("Content-Type", CONTENT_TYPE_JSON);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        TimeZone utc = TimeZone.getTimeZone("UTC");
        dateFormat.setTimeZone(utc);
        String timestamp = dateFormat.format(System.currentTimeMillis());

        JsonObject body = new JsonObject();

        body.addProperty("contents", DatatypeConverter.printBase64Binary(payload.toString().getBytes("UTF-8")));
        body.addProperty("contents_type", CONTENT_TYPE_JSON);
        body.addProperty("timestamp", timestamp);
        body.addProperty("tool_name", "sonarqube");
        body.addProperty("lifecycle_stage", "sonarqube");
        body.add("url", urls);

        StringEntity data = new StringEntity(body.toString());
        postMethod.setEntity(data);
        CloseableHttpResponse response = httpClient.execute(postMethod);
        resStr = EntityUtils.toString(response.getEntity());
        if (response.getStatusLine().toString().contains("200")) {
            // get 200 response
            printStream.println("[IBM Cloud DevOps] Upload Build Information successfully");
            return true;

        } else {
            // if gets error status
            printStream.println(
                    "[IBM Cloud DevOps] Error: Failed to upload, response status " + response.getStatusLine());

            JsonParser parser = new JsonParser();
            JsonElement element = parser.parse(resStr);
            JsonObject resJson = element.getAsJsonObject();
            if (resJson != null && resJson.has("user_error")) {
                printStream.println("[IBM Cloud DevOps] Reason: " + resJson.get("user_error"));
            }
        }
    } catch (JsonSyntaxException e) {
        printStream.println("[IBM Cloud DevOps] Invalid Json response, response: " + resStr);
    } catch (IllegalStateException e) {
        // will be triggered when 403 Forbidden
        try {
            printStream.println("[IBM Cloud DevOps] Please check if you have the access to "
                    + URLEncoder.encode(this.orgName, "UTF-8") + " org");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}

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

public static String base64en(String string) {
        return DatatypeConverter.printBase64Binary(string.getBytes());
    }

From source file:com.neurotec.samples.panels.EnrollFromScanner.java

@Override
public void actionPerformed(ActionEvent ev) {
    try {/*from   w w w  .  j av a  2 s .com*/
        if (ev.getSource() == btnRefresh) {
            updateScannerList();
        } else if (ev.getSource() == btnScan) {
            startCapturing();
        } else if (ev.getSource() == btnCancel) {
            cancelCapturing();
        } else if (ev.getSource() == btnForce) {
            FingersTools.getInstance().getClient().force();
        } else if (ev.getSource() == btnIdentifyPatient) {
            identifyPatient();
        } else if (ev.getSource() == cbShowProcessed) {
            updateShownImage();
        } else if (ev.getSource() == btnRegisterPatient) {

            String template = DatatypeConverter.printBase64Binary(subject.getTemplateBuffer().toByteArray());
            service.callRegisterPatientJavaScriptFunction(template);
        }
    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(this, e.toString(), "Error", JOptionPane.ERROR_MESSAGE);
    }
}

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

/**
 * Encode image to string/*from  w ww  .j a va  2 s . co m*/
 * @param image The image to encode
 * @param type jpeg, bmp, ...
 * @return encoded string
 */
public static String encodeToString(BufferedImage image, String type) {
    String imageString = null;
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        ImageIO.write(image, type, bos);
        byte[] imageBytes = bos.toByteArray();
        imageString = DatatypeConverter.printBase64Binary(imageBytes);
        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return imageString;
}

From source file:at.tugraz.sss.serv.SSFileU.java

public static String readPNGToBase64Str(final String pngFilePath) throws Exception {

    final DataInputStream fileReader = new DataInputStream(new FileInputStream(new File(pngFilePath)));
    final List<Byte> bytes = new ArrayList<>();
    byte[] chunk = new byte[SSSocketU.socketTranmissionSize];
    int fileChunkLength;

    while (true) {

        fileChunkLength = fileReader.read(chunk);

        if (fileChunkLength == -1) {
            break;
        }//from w w w  .  j  ava2 s.  co m

        for (int counter = 0; counter < fileChunkLength; counter++) {
            bytes.add(chunk[counter]);
        }
    }

    return "data:image/png;base64," + DatatypeConverter
            .printBase64Binary(ArrayUtils.toPrimitive(bytes.toArray(new Byte[bytes.size()])));
}