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:com.zimbra.qa.unittest.TestCalDav.java

public static void addBasicAuthHeaderForUser(HttpMethod method, Account acct, String password)
        throws UnsupportedEncodingException {
    String basicAuthEncoding = DatatypeConverter
            .printBase64Binary(String.format("%s:%s", acct.getName(), password).getBytes("UTF-8"));
    method.addRequestHeader("Authorization", "Basic " + basicAuthEncoding);
}

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

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

    // create ReduceOperator for removing records
    ReduceOperator.Builder duplicateEliminationBuilder = ReduceOperator
            .builder(DuplicateEliminationOperator.class).input(childPlan).name("DupElim");
    for (int column : dupElim.getColumns())
        KeyFactoryOperations.addKey(duplicateEliminationBuilder,
                MetadataTypesMapping.getKeyClass(dupElim.getChild().getNRSMD().getType(column)), column);
    ReduceOperator duplicateElimination = duplicateEliminationBuilder.build();

    // projection configuration
    final String encodedNRSMD = DatatypeConverter
            .printBase64Binary(SerializationUtils.serialize(dupElim.getNRSMD()));
    duplicateElimination.setParameter(PACTOperatorsConfiguration.NRSMD1_BINARY.toString(), encodedNRSMD);
    final String encodedDuplicateEliminationColumns = DatatypeConverter
            .printBase64Binary(SerializationUtils.serialize(dupElim.getColumns()));
    duplicateElimination.setParameter(PACTOperatorsConfiguration.DUP_ELIM_COLUMNS_BINARY.toString(),
            encodedDuplicateEliminationColumns);

    return new Operator[] { duplicateElimination };
}

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

@Override
public ShareExercisesResult submitExercises(Problem[] problems, String repoUsername, String repoPassword)
        throws CloudCoderAuthenticationException {
    logger.warn("Sharing " + problems.length + " exercises");

    // create the result place holder
    ShareExercisesResult result = new ShareExercisesResult(problems.length);

    if (problems.length == 0) {
        result.failAll("No problems to be shared!");
        return result;
    }//from   w w  w . j  a v a 2 s.  co m

    // Only a course instructor may share an exercise.
    User authenticatedUser = ServletUtil.checkClientIsAuthenticated(getThreadLocalRequest(),
            GetCoursesAndProblemsServiceImpl.class);
    Course course = new Course();
    course.setId(problems[0].getCourseId());
    Database.getInstance().reloadModelObject(course);
    CourseRegistrationList regList = Database.getInstance().findCourseRegistrations(authenticatedUser, course);
    if (!regList.isInstructor()) {
        result.failAll("You must be an instructor to share an exercise");
        return result;
    }

    // Get the exercise repository URL
    ConfigurationSetting repoUrlSetting = Database.getInstance()
            .getConfigurationSetting(ConfigurationSettingName.PUB_REPOSITORY_URL);
    if (repoUrlSetting == null) {
        result.failAll("URL of exercise repository is not configured");
        return result;
    }
    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);

    // Now go through and upload each problem
    // For now, we do this one at a time
    // In the future we could send problems and test cases 
    // to the repo in bulk, and add a new web service to handle it

    for (Problem p : problems) {
        // Look up the test cases
        List<TestCase> testCaseList = Database.getInstance().getTestCasesForProblem(p.getProblemId());
        ProblemAndTestCaseList exercise = new ProblemAndTestCaseList();
        exercise.setProblem(p);
        exercise.setTestCaseList(testCaseList);

        // 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) {
            // fail remaining test cases and return our results thus far
            // some exercises may have been successfully shared
            result.failRemaining("Could not convert exercise to JSON: " + e.getMessage());
            return result;
        }
        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);
                exercise.getProblem().setProblemAuthorship(ProblemAuthorship.IMPORTED);
                Database.getInstance().storeProblemAndTestCaseList(exercise, course, authenticatedUser);
                result.success();
            } else if (statusLine.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                result.failRemaining("Authentication with repository failed - incorrect username/password?");
                return result;
            } else {
                result.failRemaining(
                        "Failed to publish exercise to repository: " + statusLine.getReasonPhrase());
                return result;
            }
        } catch (ClientProtocolException e) {
            result.failRemaining("Error sending exercise to repository: " + e.getMessage());
            return result;
        } catch (IOException e) {
            result.failRemaining("Error sending exercise to repository: " + e.getMessage());
            return result;
        } finally {
            client.getConnectionManager().shutdown();
        }
    }
    result.allSucceeded("Successfully uploaded " + problems.length + " exercise to repository.  Thanks!");
    return result;
}

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

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

    Operator<Record> aggregation;/*  w w w .ja v a2 s . c  o m*/
    if (aggr.getAggregationPath().length > 1) {
        // create MapOperator for aggregating
        aggregation = MapOperator.builder(NestedAggregationOperator.class).input(childPlan).name("Aggr")
                .build();

        // aggregation configuration
        final String encodedNRSMD = DatatypeConverter
                .printBase64Binary(SerializationUtils.serialize(aggr.getNRSMD()));
        aggregation.setParameter(PACTOperatorsConfiguration.NRSMD1_BINARY.toString(), encodedNRSMD);
        final String aggregationPath = DatatypeConverter
                .printBase64Binary(SerializationUtils.serialize(aggr.getAggregationPath()));
        aggregation.setParameter(PACTOperatorsConfiguration.AGGREGATION_PATH_BINARY.toString(),
                aggregationPath);
        final String aggregationType = DatatypeConverter
                .printBase64Binary(SerializationUtils.serialize(aggr.getAggregationType()));
        aggregation.setParameter(PACTOperatorsConfiguration.AGGREGATION_TYPE_BINARY.toString(),
                aggregationType);
    } else {
        //First, we create the NRSMD of the (pre) groupBy
        NestedMetadata groupByNRSMD = aggr.getNRSMD();
        MetadataTypes[] attScanMeta = new MetadataTypes[1];
        attScanMeta[0] = MetadataTypes.INTEGER_TYPE;
        final NestedMetadata auxColumnNRSMD = new NestedMetadata(1, attScanMeta);
        groupByNRSMD = NestedMetadataUtils.appendNRSMD(groupByNRSMD, auxColumnNRSMD);

        //Then, we create ReduceOperator for grouping using the document ID column
        ReduceOperator.Builder groupByBuilder = ReduceOperator.builder(GroupByWithAggregationOperator.class)
                .input(childPlan).name("GroupByAgg");
        KeyFactoryOperations.addKey(groupByBuilder, StringValue.class, aggr.getDocumentIDColumn());
        ReduceOperator groupBy = groupByBuilder.build();

        // groupBy configuration
        final String encodedNRSMDGroupBy = DatatypeConverter
                .printBase64Binary(SerializationUtils.serialize(groupByNRSMD));
        groupBy.setParameter(PACTOperatorsConfiguration.NRSMD1_BINARY.toString(), encodedNRSMDGroupBy);

        final String encodedGroupByColumns = DatatypeConverter
                .printBase64Binary(SerializationUtils.serialize(new int[] {}));
        groupBy.setParameter(PACTOperatorsConfiguration.GROUP_BY_COLUMNS_BINARY.toString(),
                encodedGroupByColumns);

        final NestedMetadata childNRSMD = aggr.getChild().getNRSMD();
        int[] nestColumns = new int[childNRSMD.getColNo()];
        for (int i = 0; i < childNRSMD.getColNo(); i++)
            nestColumns[i] = i;
        final String encodedNestColumns = DatatypeConverter
                .printBase64Binary(SerializationUtils.serialize(nestColumns));
        groupBy.setParameter(PACTOperatorsConfiguration.NEST_COLUMNS_BINARY.toString(), encodedNestColumns);

        groupBy.setParameter(PACTOperatorsConfiguration.AGGREGATION_COLUMN_INT.toString(),
                aggr.getAggregationPath()[0]);

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

        groupBy.setParameter(PACTOperatorsConfiguration.EXCLUDE_NESTED_FIELD_BOOLEAN.toString(),
                aggr.isExcludeNestedField());

        groupBy.setParameter(PACTOperatorsConfiguration.ATTACH_DUMMY_COLUMN_BOOLEAN.toString(), true);

        // create ReduceOperator for aggregating
        ReduceOperator.Builder aggregationBuilder = ReduceOperator.builder(PostAggregationOperator.class)
                .input(groupBy).name("PostAggr");
        KeyFactoryOperations.addKey(aggregationBuilder, IntValue.class, groupByNRSMD.colNo - 1);
        aggregation = aggregationBuilder.build();

        //Post-aggregation configuration
        final String encodedNRSMDPostAggregation = DatatypeConverter
                .printBase64Binary(SerializationUtils.serialize(aggr.getNRSMD()));
        aggregation.setParameter(PACTOperatorsConfiguration.NRSMD1_BINARY.toString(),
                encodedNRSMDPostAggregation);
        if (aggr.isExcludeNestedField())
            aggregation.setParameter(PACTOperatorsConfiguration.POST_AGGREGATION_COLUMN_INT.toString(), 0);
        else {
            aggregation.setParameter(PACTOperatorsConfiguration.NESTED_RECORDS_COLUMN_INT.toString(), 0);
            aggregation.setParameter(PACTOperatorsConfiguration.POST_AGGREGATION_COLUMN_INT.toString(), 1);
        }

        aggregation.setParameter(PACTOperatorsConfiguration.AGGREGATION_TYPE_BINARY.toString(),
                encodedAggregationType);

        aggregation.setParameter(PACTOperatorsConfiguration.EXCLUDE_NESTED_FIELD_BOOLEAN.toString(),
                aggr.isExcludeNestedField());
    }

    return new Operator[] { aggregation };
}

From source file:com.orthancserver.SelectImageDialog.java

public String Serialize() {
    JSONArray servers = new JSONArray();

    for (int i = 0; i < root_.getChildCount(); i++) {
        MyTreeNode node = (MyTreeNode) root_.getChildAt(i);
        servers.add(node.GetConnection().Serialize());
    }//from  w ww. j a va 2 s. com

    String config = servers.toJSONString();
    return DatatypeConverter.printBase64Binary(config.getBytes());
}

From source file:com.sitewhere.rest.service.SiteWhereClient.java

/**
 * Encode the username and password to make the authorization header.
 * // www . j  a  v  a2s.  c om
 * @return
 */
protected String getAuthHeader() {
    String token = getUsername() + ":" + getPassword();
    String encoded = DatatypeConverter.printBase64Binary(token.getBytes());
    return "Basic " + encoded;
}

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

/**
 * Creates a base 64 encoded string from the given input string.
 * @param input the value to encode/*  w  w  w  . ja  v  a2  s  . co  m*/
 * @return base 64 encoded string
 */
public static String encodeBase64(String input) {
    return DatatypeConverter.printBase64Binary(input.getBytes(StandardCharsets.UTF_8));
}

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

/**
 * Creates a base 64 encoded string from the given input bytes.
 * @param input the value to encode//from  w  w  w  . j  a  va 2 s  .c  o  m
 * @return base 64 encoded string
 */
public static String encodeBase64(byte[] input) {
    return DatatypeConverter.printBase64Binary(input);
}

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

public static String readImageToBase64Str(final String filePath, final Integer transmissionSize) throws SSErr {

    try {//from   w  w  w. ja  v  a2 s.com
        final DataInputStream fileReader = new DataInputStream(new FileInputStream(new File(filePath)));
        final List<Byte> bytes = new ArrayList<>();
        byte[] chunk = new byte[transmissionSize];
        int fileChunkLength;

        while (true) {

            fileChunkLength = fileReader.read(chunk);

            if (fileChunkLength == -1) {
                break;
            }

            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()])));
    } catch (Exception error) {
        SSServErrReg.regErrThrow(error);
        return null;
    }
}

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

public String encrypt(String key, String data) throws Exception {
    Key keySpec = new SecretKeySpec(key.getBytes(), ALGO);
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.ENCRYPT_MODE, keySpec);
    byte[] encVal = c.doFinal(data.getBytes());
    String encryptedValue = DatatypeConverter.printBase64Binary(encVal);
    return encryptedValue;
}