Example usage for java.util Base64 getDecoder

List of usage examples for java.util Base64 getDecoder

Introduction

In this page you can find the example usage for java.util Base64 getDecoder.

Prototype

public static Decoder getDecoder() 

Source Link

Document

Returns a Decoder that decodes using the Basic type base64 encoding scheme.

Usage

From source file:io.dockstore.webservice.helpers.GitHubSourceCodeRepo.java

private String extractGitHubContents(List<RepositoryContents> cwlContents) {
    String encoded = cwlContents.get(0).getContent().replace("\n", "");
    byte[] decode = Base64.getDecoder().decode(encoded);
    return new String(decode, StandardCharsets.UTF_8);
}

From source file:org.wso2.carbon.siddhi.editor.core.internal.EditorMicroservice.java

@POST
@Path("/workspace/export")
@Produces("application/json")
public Response export(String payload) {
    try {/*  w  w  w  .jav  a 2s  . c  om*/
        String location = "";
        String configName = "";
        String config = "";
        Matcher locationMatcher = Pattern.compile("location=(.*?)&configName").matcher(payload);
        while (locationMatcher.find()) {
            location = locationMatcher.group(1);
        }
        Matcher configNameMatcher = Pattern.compile("configName=(.*?)&").matcher(payload);
        while (configNameMatcher.find()) {
            configName = configNameMatcher.group(1);
        }
        String[] splitConfigContent = payload.split("config=");
        if (splitConfigContent.length > 1) {
            config = splitConfigContent[1];
        }
        byte[] base64Config = Base64.getDecoder().decode(config);
        byte[] base64ConfigName = Base64.getDecoder().decode(configName);
        byte[] base64Location = Base64.getDecoder().decode(location);
        Files.write(Paths.get(new String(base64Location, Charset.defaultCharset())
                + System.getProperty(FILE_SEPARATOR) + new String(base64ConfigName, Charset.defaultCharset())),
                base64Config);
        JsonObject entity = new JsonObject();
        entity.addProperty(STATUS, SUCCESS);
        return Response.status(Response.Status.OK).entity(entity).type(MediaType.APPLICATION_JSON).build();
    } catch (AccessDeniedException e) {
        Map<String, String> errorMap = new HashMap<>(1);
        errorMap.put("Error", "File access denied. You don't have enough permission to access");
        return Response.serverError().entity(errorMap).build();
    } catch (IOException e) {
        return Response.serverError().entity("failed." + e.getMessage()).build();
    } catch (Throwable ignored) {
        return Response.serverError().entity("failed").build();
    }
}

From source file:edu.kit.dama.mdm.content.oaipmh.impl.SimpleOAIPMHRepository.java

/**
 * Get all digital objects according to the arguments set at the provided
 * OAIPMHBuilder.//w w  w .j a  va  2s  .c o m
 *
 * Depending of the values ot 'from', 'until' and 'metadataPrefix' set at
 * the OAIPMHBuilder the result list may contain all or a reduced list of
 * objects. The list might also be empty. In that case a proper OAI-PMH
 * error must be created by the caller.
 *
 * @param builder The OAIPMHBuilder.
 *
 * @return A list of entities which might be empty.
 */
private List<DigitalObject> getEntities(OAIPMHBuilder builder) {
    List<DigitalObject> results = new ArrayList<>();

    String prefix = builder.getMetadataPrefix();
    LOGGER.debug("Getting entities for metadata prefix {} from repository.", prefix);
    IMetaDataManager mdm = MetaDataManagement.getMetaDataManagement().getMetaDataManager();
    mdm.setAuthorizationContext(getAuthorizationContext());
    try {
        LOGGER.debug("Checking request for resumption token");
        String resumptionToken = builder.getResumptionToken();
        int currentCursor = 0;
        int overallCount = 0;
        //check resumption token
        if (resumptionToken != null) {
            String tokenValue = new String(
                    Base64.getDecoder().decode(URLDecoder.decode(resumptionToken, "UTF-8")));
            LOGGER.debug("Found token with value {}", tokenValue);
            String[] elements = tokenValue.split("/");
            if (elements.length != 2) {
                LOGGER.error("Invalid resumption token. Returning OAI-PMH error BAD_RESUMPTION_TOKEN.");
                builder.addError(OAIPMHerrorcodeType.BAD_RESUMPTION_TOKEN, null);
                return new ArrayList<>();
            }
            try {
                LOGGER.debug("Parsing token values.");
                currentCursor = Integer.parseInt(elements[0]);
                overallCount = Integer.parseInt(elements[1]);
                LOGGER.debug("Obtained {} as current cursor from token.", currentCursor);
            } catch (NumberFormatException ex) {
                //log error
                builder.addError(OAIPMHerrorcodeType.BAD_RESUMPTION_TOKEN, null);
                return new ArrayList<>();
            }
        } else {
            LOGGER.debug("No resumption token found.");
        }

        if (DC_SCHEMA.getSchemaIdentifier().equals(prefix)) {
            LOGGER.debug("Using Dublin Core schema handling.");
            //handle default schema which is supported by ALL objects, so no complex query is needed.
            Date from = builder.getFromDate();
            Date until = builder.getUntilDate();
            if (from != null && until != null) {
                LOGGER.debug("Getting all digital objects from {} until {}.", from, until);
                results = mdm.findResultList(
                        "SELECT o FROM DigitalObject o WHERE o.uploadDate>=?1 AND o.uploadDate <= ?2",
                        new Object[] { from, until }, DigitalObject.class, currentCursor, maxElementsPerList);
                overallCount = (overallCount == 0) ? mdm.findSingleResult(
                        "SELECT COUNT(o) FROM DigitalObject o WHERE o.uploadDate>=?1 AND o.uploadDate <= ?2",
                        new Object[] { from, until }, Number.class).intValue() : overallCount;
            } else if (from != null && until == null) {
                LOGGER.debug("Getting all digital objects from {}.", from);
                results = mdm.findResultList("SELECT o FROM DigitalObject o WHERE o.uploadDate >= ?1",
                        new Object[] { from }, DigitalObject.class, currentCursor, maxElementsPerList);
                overallCount = (overallCount == 0)
                        ? mdm.findSingleResult("SELECT COUNT(o) FROM DigitalObject o WHERE o.uploadDate >= ?1",
                                new Object[] { from }, Number.class).intValue()
                        : overallCount;
            } else if (from == null && until != null) {
                LOGGER.debug("Getting all digital objects until {}.", until);
                results = mdm.findResultList("SELECT o FROM DigitalObject o WHERE o.uploadDate <= ?1",
                        new Object[] { until }, DigitalObject.class, currentCursor, maxElementsPerList);
                overallCount = (overallCount == 0)
                        ? mdm.findSingleResult("SELECT COUNT(o) FROM DigitalObject o WHERE o.uploadDate <= ?1",
                                new Object[] { until }, Number.class).intValue()
                        : overallCount;
            } else {
                LOGGER.debug("Getting all digital object.");
                results = mdm.findResultList("SELECT o FROM DigitalObject o", DigitalObject.class,
                        currentCursor, maxElementsPerList);
                overallCount = (overallCount == 0)
                        ? mdm.findSingleResult("SELECT COUNT(o) FROM DigitalObject o", Number.class).intValue()
                        : overallCount;
            }
        } else {

            //@TODO Check where to obtain the metadata document if no MetadataIndexingTask entry is available, e.g. via DataOrganization?
            LOGGER.debug("Using custom schema handling for prefix {}.", prefix);
            //filter by special schema which might not be supported by all objects
            Date from = builder.getFromDate();
            Date until = builder.getUntilDate();
            if (from != null && until != null) {
                LOGGER.debug("Getting all digital objects from {} until {}.", from, until);
                results = mdm.findResultList(
                        "SELECT o FROM DigitalObject o,MetadataIndexingTask t WHERE o.uploadDate>=?1 AND o.uploadDate <= ?2 AND t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?3",
                        new Object[] { from, until, prefix }, DigitalObject.class, currentCursor,
                        maxElementsPerList);
                overallCount = (overallCount == 0) ? mdm.findSingleResult(
                        "SELECT o FROM DigitalObject o,MetadataIndexingTask t WHERE o.uploadDate>=?1 AND o.uploadDate <= ?2 AND t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?3",
                        new Object[] { from, until, prefix }, Number.class).intValue() : overallCount;
            } else if (from != null && until == null) {
                LOGGER.debug("Getting all digital objects from {}.", from);
                results = mdm.findResultList(
                        "SELECT o FROM DigitalObject o,MetadataIndexingTask t WHERE o.uploadDate>=?1 AND t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?2",
                        new Object[] { from, prefix }, DigitalObject.class, currentCursor, maxElementsPerList);
                overallCount = (overallCount == 0) ? mdm.findSingleResult(
                        "SELECT COUNT(o) FROM DigitalObject o,MetadataIndexingTask t WHERE o.uploadDate>=?1 AND t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?2",
                        new Object[] { from, prefix }, Number.class).intValue() : overallCount;
            } else if (from == null && until != null) {
                LOGGER.debug("Getting all digital objects until {}.", until);
                results = mdm.findResultList(
                        "SELECT o FROM DigitalObject o,MetadataIndexingTask t WHERE o.uploadDate <= ?1 AND t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?2",
                        new Object[] { until, prefix }, DigitalObject.class, currentCursor, maxElementsPerList);
                overallCount = (overallCount == 0) ? mdm.findSingleResult(
                        "SELECT COUNT(o) FROM DigitalObject o,MetadataIndexingTask t WHERE o.uploadDate <= ?1 AND t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?2",
                        new Object[] { until, prefix }, Number.class).intValue() : overallCount;
            } else {
                LOGGER.debug("Getting all digital object.");
                results = mdm.findResultList(
                        "SELECT o FROM DigitalObject o,MetadataIndexingTask t WHERE t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?1",
                        new Object[] { prefix }, DigitalObject.class, currentCursor, maxElementsPerList);
                overallCount = (overallCount == 0) ? mdm.findSingleResult(
                        "SELECT COUNT(o) FROM DigitalObject o,MetadataIndexingTask t WHERE t.digitalObjectId=o.digitalObjectIdentifier AND t.schemaReference.schemaIdentifier=?1",
                        new Object[] { prefix }, Number.class).intValue() : overallCount;
            }
        }

        LOGGER.debug("Setting next resumption token.");
        if (currentCursor + maxElementsPerList > overallCount) {
            LOGGER.debug(
                    "Cursor exceeds element count, no more elements available. Setting resumption token to 'null'.");
            //lsit complete, add no resumptiontoken
            builder.setResumptionToken(null);
        } else {
            ResumptionTokenType token = new ResumptionTokenType();
            //set list size
            token.setCompleteListSize(BigInteger.valueOf(overallCount));
            //set current cursor
            token.setCursor(BigInteger.valueOf(currentCursor + results.size()));
            LOGGER.debug("Setting new resumption token with cursor at position " + token.getCursor());
            //we set no expiration as the token never expires
            String value = token.getCursor().intValue() + "/" + token.getCompleteListSize().intValue();
            LOGGER.debug("Setting resumption token value to {}.", value);
            token.setValue(URLEncoder.encode(Base64.getEncoder().encodeToString(value.getBytes()), "UTF-8"));
            builder.setResumptionToken(token);
        }
    } catch (UnauthorizedAccessAttemptException | UnsupportedEncodingException ex) {
        //error
        LOGGER.error("Failed to get results from repository. Returning empty list.", ex);
    } finally {
        mdm.close();
    }
    return results;
}

From source file:com.mercer.cpsg.swarm.oidc.deployment.OIDCAuthenticationMechanism.java

protected String restoreState(String state, HttpServerExchange exchange) throws Exception {
    if (oidcProvider.isCheckNonce()) {
        String previousState = (String) getSession(exchange).getAttribute(LOCATION_KEY);
        return previousState != null && previousState.equals(state) ? state : null;
    } else {/*from  w w w  . ja v a 2s .co m*/
        byte[] secureReturnURL = Base64.getDecoder().decode(state);
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, stateKey);
        try {
            secureReturnURL = cipher.doFinal(secureReturnURL);
            return new String(secureReturnURL);
        } catch (Exception e) {
            // non-critical exception
            LOG.log(Level.FINER, "State decryption failed", e);
            return null;
        }
    }
}

From source file:com.wso2telco.proxy.entity.ServerInitiatedServiceEndpoints.java

private RSAPublicKey loadPublicKey(String publicKeyContent) throws GeneralSecurityException {
    KeyFactory kf = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyContent));
    return (RSAPublicKey) kf.generatePublic(pubSpec);
}

From source file:com.exalttech.trex.util.Util.java

/**
 * De-serialize string to object//from w  ww  . ja v  a  2  s  . c  om
 *
 * @param serializedStriing
 * @return
 */
public static Object deserializeStringToObject(String serializedStriing) {
    try {
        byte[] data = Base64.getDecoder().decode(serializedStriing);
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(data));
        Object o = ois.readObject();
        ois.close();
        return o;
    } catch (IOException | ClassNotFoundException ex) {
        LOG.error("Error deserializing string to object", ex);
        return null;
    }
}

From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java

/**
 * Enroll the user with member service/*w w  w  . j  a v  a  2  s .co  m*/
 *
 * @param user   Identity name to enroll
 * @param secret Secret returned via registration
 * @param req    Enrollment request with the following fields: hosts, profile, csr, label, keypair
 * @return enrollment
 * @throws EnrollmentException
 * @throws InvalidArgumentException
 */

public Enrollment enroll(String user, String secret, EnrollmentRequest req)
        throws EnrollmentException, InvalidArgumentException {

    logger.debug(format("url:%s enroll user: %s", url, user));

    if (Utils.isNullOrEmpty(user)) {
        throw new InvalidArgumentException("enrollment user is not set");
    }
    if (Utils.isNullOrEmpty(secret)) {
        throw new InvalidArgumentException("enrollment secret is not set");
    }

    if (cryptoSuite == null) {
        throw new InvalidArgumentException("Crypto primitives not set.");
    }

    setUpSSL();

    try {
        String pem = req.getCsr();
        KeyPair keypair = req.getKeyPair();
        if (null != pem && keypair == null) {
            throw new InvalidArgumentException(
                    "If certificate signing request is supplied the key pair needs to be supplied too.");
        }
        if (keypair == null) {
            logger.debug("[HFCAClient.enroll] Generating keys...");

            // generate ECDSA keys: signing and encryption keys
            keypair = cryptoSuite.keyGen();

            logger.debug("[HFCAClient.enroll] Generating keys...done!");
        }

        if (pem == null) {
            String csr = cryptoSuite.generateCertificationRequest(user, keypair);
            req.setCSR(csr);
        }

        if (caName != null && !caName.isEmpty()) {
            req.setCAName(caName);
        }
        String body = req.toJson();

        String responseBody = httpPost(url + HFCA_ENROLL, body, new UsernamePasswordCredentials(user, secret));

        logger.debug("response:" + responseBody);

        JsonReader reader = Json.createReader(new StringReader(responseBody));
        JsonObject jsonst = (JsonObject) reader.read();

        boolean success = jsonst.getBoolean("success");
        logger.debug(format("[HFCAClient] enroll success:[%s]", success));

        if (!success) {
            throw new EnrollmentException(
                    format("FabricCA failed enrollment for user %s response success is false.", user));
        }

        JsonObject result = jsonst.getJsonObject("result");
        if (result == null) {
            throw new EnrollmentException(
                    format("FabricCA failed enrollment for user %s - response did not contain a result", user));
        }

        Base64.Decoder b64dec = Base64.getDecoder();

        String signedPem = new String(b64dec.decode(result.getString("Cert").getBytes(UTF_8)));
        logger.debug(format("[HFCAClient] enroll returned pem:[%s]", signedPem));

        JsonArray messages = jsonst.getJsonArray("messages");
        if (messages != null && !messages.isEmpty()) {
            JsonObject jo = messages.getJsonObject(0);
            String message = format("Enroll request response message [code %d]: %s", jo.getInt("code"),
                    jo.getString("message"));
            logger.info(message);
        }
        logger.debug("Enrollment done.");

        return new X509Enrollment(keypair, signedPem);

    } catch (EnrollmentException ee) {
        logger.error(format("url:%s, user:%s  error:%s", url, user, ee.getMessage()), ee);
        throw ee;

    } catch (Exception e) {
        EnrollmentException ee = new EnrollmentException(format("Url:%s, Failed to enroll user %s ", url, user),
                e);
        logger.error(e.getMessage(), e);
        throw ee;
    }

}

From source file:XMLParser.java

public static String decrypt(String cryptedXML, String key) {
    int c;/*from  w ww  . ja v a2 s.co  m*/
    String finalXML = "";
    byte[] str = Base64.getDecoder().decode(cryptedXML);
    for (int i = 0; i < str.length; i++) {
        c = str[i];
        c -= key.charAt((i + 1) % key.length());
        finalXML += (char) (c & 255);
    }
    return finalXML;
}

From source file:no.asgari.civilization.server.action.PlayerAction.java

/**
 * Returns the id to the player created/*from w  ww  .j  a  v a 2s.c o  m*/
 *
 * @return the id of the newly created player
 * @throws PlayerExistException - Throws this exception if username already exists
 */
@SneakyThrows
public String createPlayer(String usernameEncoded, String passwordEncoded, String emailEncoded)
        throws PlayerExistException {
    Preconditions.checkNotNull(usernameEncoded);
    Preconditions.checkNotNull(passwordEncoded);
    Preconditions.checkNotNull(emailEncoded);

    String username = URLDecoder.decode(usernameEncoded, "UTF-8");
    String email = URLDecoder.decode(emailEncoded, "UTF-8");
    String password = URLDecoder.decode(passwordEncoded, "UTF-8");

    if (CivSingleton.instance().playerCache().asMap().containsValue(username)) {
        throw new PlayerExistException();
    }

    Player player = new Player();
    player.setUsername(username);
    String decodedPassword = new String(Base64.getDecoder().decode(password), "UTF-8");

    player.setPassword(DigestUtils.sha1Hex(decodedPassword));
    player.setEmail(email);
    WriteResult<Player, String> insert = playerCollection.insert(player);
    log.info(String.format("Saving player with id %s", insert.getSavedId()));
    return insert.getSavedId();
}

From source file:br.eti.ns.nscteapiclientexample.EmissaoCTeForm.java

private void cmdBaixarCTeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdBaixarCTeActionPerformed
    String chCTe = txtChave.getText();
    String tokenAcesso = txtTokenAcesso.getText();

    if (StringUtils.isBlank(tokenAcesso)) {
        JOptionPane.showMessageDialog(null, "O Token de Acesso deve ser informado");
        return;//from   w  w w  .ja v a 2 s. c  o m
    }

    if (StringUtils.isBlank(chCTe)) {
        JOptionPane.showMessageDialog(null, "A chave do CT-e deve ser informada");
        return;
    }

    ApiCTeService.DownloadCTeParam downloadCTeParam = new ApiCTeService.DownloadCTeParam();
    downloadCTeParam.xAuthToken = tokenAcesso;
    downloadCTeParam.chCTe = chCTe;
    downloadCTeParam.tpAmb = 2;
    downloadCTeParam.tpDown = "P";

    try {
        Response respostaServidor = ApiCTeService.downloadCTe(downloadCTeParam);
        String corpoDaResposta = respostaServidor.readEntity(String.class);

        StringBuilder retornoTexto = new StringBuilder();
        retornoTexto.append("Status HTTP: ").append(respostaServidor.getStatus()).append(" - ")
                .append(respostaServidor.getStatusInfo().getReasonPhrase()).append("\n");

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode respostaJson = objectMapper.readTree(corpoDaResposta);

            String pdfBase64 = respostaJson.get("pdf").asText();

            Path tempPDF = Files.createTempFile(null, ".pdf");
            //O arquivo PDF do DACTE do CT-e e enviando em encoding Base64,
            // por isso antes de salvar no arquivo temporario precisamos
            // decodificar de Base64 para bytes
            Files.write(tempPDF, Base64.getDecoder().decode(pdfBase64));

            //Abre o arquivo PDF em tela com o leitor de PDFs padrao
            Desktop.getDesktop().open(tempPDF.toFile());

        } catch (Exception e) {
            retornoTexto.append("\n\nDados retornados pelo servidor:\n").append(corpoDaResposta);
        }

        textRetornoServidor.setText(retornoTexto.toString());

    } catch (Exception ex) {
        textRetornoServidor.setText("Erro: " + ex.getMessage());
    }
}