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:com.cts.ptms.carrier.ups.UPSHTTPClient.java

/**
 * This method triggers the shipping label generation process
 *///w w  w .ja v  a2  s  .c o m
public ShipmentOrder generateShippingLabel(ShippingInfoDO shippingInfoDO, ShipmentRequest request)
        throws Exception {

    //Load the properties file 
    loadProperties();

    // JAXB Context of AccessRequest.java
    JAXBContext accessRequestJAXBC = JAXBContext.newInstance(AccessRequest.class.getPackage().getName());
    Marshaller accessRequestMarshaller = accessRequestJAXBC.createMarshaller();

    //JAXB Context of ShipmentConfirmRequest.java
    JAXBContext shipConfirmRequestJAXBC = JAXBContext.newInstance(ShipmentConfirmRequest.class);
    Marshaller shipConfirmRequestMarshaller = shipConfirmRequestJAXBC.createMarshaller();

    //JAXB Context of ShipmentConfirmResponse.java
    JAXBContext shipConfirmJAXBC = JAXBContext.newInstance(ShipmentConfirmResponse.class);
    Unmarshaller shipConfirmUnmarshaller = shipConfirmJAXBC.createUnmarshaller();

    //JAXB Context of ShipmentAcceptRequest.java
    JAXBContext shipAcceptJaxb = JAXBContext.newInstance(ShipmentAcceptRequest.class);
    Marshaller shipAcceptRequestMarshaller = shipAcceptJaxb.createMarshaller();

    //JAXB Context of ShipmentAcceptResponse.Java
    JAXBContext shipAcceptAXBC = JAXBContext.newInstance(ShipmentAcceptResponse.class);
    Unmarshaller shipAcceptUnmarshaller = shipAcceptAXBC.createUnmarshaller();

    StringWriter strWriter = new StringWriter();
    accessRequestMarshaller.marshal(shippingInfoDO.getUpsSecurity(), strWriter);
    shipConfirmRequestMarshaller.marshal(shippingInfoDO.getConfirmRequest(), strWriter);
    strWriter.flush();
    strWriter.close();
    String confirmInput = strWriter.getBuffer().toString();
    //--confirmInput = confirmInput.replace(ShippingConstants.XML_NAMESPACE, "");
    String strResults = contactService(confirmInput,
            properties.getProperty(ShippingConstants.SHIPPING_CONFIRM_URL));
    //--strResults = strResults.replace(ShippingConstants.SHIP_Response_TAG,ShippingConstants.ship_Response_Replace);
    String result = "";
    if (strResults.indexOf(ShippingConstants.error_Open_tag) != -1) {
        result = strResults.substring(strResults.indexOf(ShippingConstants.error_Open_tag),
                strResults.indexOf(ShippingConstants.error_Close_tag));
        result = result.replace(ShippingConstants.error_Open_tag, "");
    }
    ByteArrayInputStream input = new ByteArrayInputStream(strResults.getBytes());
    ShipmentConfirmResponse shipconfirmResponse = new ShipmentConfirmResponse();
    if (null != shipconfirmResponse.getResponse()) {
        shipconfirmResponse.getResponse().getError().add(new Error());
    }
    shipconfirmResponse = (ShipmentConfirmResponse) shipConfirmUnmarshaller.unmarshal(input);
    if (shipconfirmResponse.getResponse().getResponseStatusCode().equals("1")) {
        com.cts.ptms.model.accept.request.ObjectFactory acceptObjectFactory = new com.cts.ptms.model.accept.request.ObjectFactory();
        //ShipmentAcceptRequestObjectFactory acceptObjectFactory = new ShipmentAcceptRequestObjectFactory();
        ShipmentAcceptRequest shipAcceptRequest = acceptObjectFactory.createShipmentAcceptRequest();
        ShipmentAcceptRequest shipmentAcceptRequest = populateShipAcceptRequest(shipAcceptRequest,
                shipconfirmResponse);

        StringWriter strWriterResponse = new StringWriter();
        accessRequestMarshaller.marshal(shippingInfoDO.getUpsSecurity(), strWriterResponse);
        shipAcceptRequestMarshaller.marshal(shipmentAcceptRequest, strWriterResponse);
        strWriterResponse.flush();
        strWriterResponse.close();
        String acceptInput = strWriterResponse.getBuffer().toString();
        //--acceptInput = acceptInput.replace(ShippingConstants.XML_NAMESPACE, "");
        String strAcceptResults = contactService(acceptInput,
                properties.getProperty(ShippingConstants.SHIPPING_ACCEPT_URL));
        //--strAcceptResults = strAcceptResults.replace(ShippingConstants.SHIP_Accept_TAG,ShippingConstants.ship_Accept_Replace);
        ByteArrayInputStream inputAccept = new ByteArrayInputStream(strAcceptResults.getBytes());
        Object objectAccept = shipAcceptUnmarshaller.unmarshal(inputAccept);
        ShipmentAcceptResponse shipAcceptResponse = (ShipmentAcceptResponse) objectAccept;
        if (!shipAcceptResponse.getResponse().getResponseStatusDescription().equalsIgnoreCase("FAILURE")) {
            String imageSrc = shipAcceptResponse.getShipmentResults().getPackageResults().get(0).getLabelImage()
                    .getGraphicImage();
            byte[] decoded = Base64.getDecoder().decode(imageSrc);
            generateShippingLabelPDF(decoded,
                    shipAcceptResponse.getShipmentResults().getShipmentIdentificationNumber(), shippingInfoDO,
                    request);
            if (null != shipAcceptResponse.getShipmentResults().getForm()) {
                String formInfo = shipAcceptResponse.getShipmentResults().getForm().getImage()
                        .getGraphicImage();
                String formExtn = shipAcceptResponse.getShipmentResults().getForm().getImage().getImageFormat()
                        .getCode();
                String formDocType = shipAcceptResponse.getShipmentResults().getForm().getClass()
                        .getSimpleName();
                byte[] intlForms = Base64.getDecoder().decode(formInfo);
                generateShippingForms(intlForms,
                        shipAcceptResponse.getShipmentResults().getShipmentIdentificationNumber(), formDocType,
                        formExtn);
            }
            return createShipmentResposeObj(null, shipAcceptResponse);
        } else {
            return createShipmentResposeObj(null, shipAcceptResponse);
        }
    } else {
        shipconfirmResponse.getResponse().getError().get(0).setErrorDescription(result);
        return createShipmentResposeObj(shipconfirmResponse, null);
    }
}

From source file:eu.vital.vitalcep.collector.Collector.java

private static String decrypt(String property) throws GeneralSecurityException, IOException {
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
    Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
    pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
    return new String(Base64.getDecoder().decode(property), StandardCharsets.UTF_8);
}

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

@GET
@Path("/workspace/listFiles/workspace")
@Produces("application/json")
public Response filesInWorkspacePath(@QueryParam("path") String relativePath) {
    try {/*from   ww  w . j  av  a  2  s  . c  o  m*/
        String location = (Paths.get(Constants.RUNTIME_PATH, Constants.DIRECTORY_DEPLOYMENT)).toString();
        java.nio.file.Path pathLocation = SecurityUtil.resolvePath(Paths.get(location).toAbsolutePath(),
                Paths.get(new String(Base64.getDecoder().decode(relativePath), Charset.defaultCharset())));
        return Response.status(Response.Status.OK).entity(workspace.listFilesInPath(pathLocation))
                .type(MediaType.APPLICATION_JSON).build();
    } catch (IOException e) {
        return Response.serverError().entity("failed." + e.getMessage()).build();
    } catch (Throwable ignored) {
        return Response.serverError().entity("failed").build();
    }
}

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

@POST
@Path("/workspace/exists/workspace")
@Produces("application/json")
public Response fileExistsAtWorkspace(String payload) {
    try {//from   w w  w.j ava2 s . c om
        String configName = "";
        String[] splitConfigContent = payload.split("configName=");
        if (splitConfigContent.length > 1) {
            configName = splitConfigContent[1];
        }
        byte[] base64ConfigName = Base64.getDecoder().decode(configName);
        String location = (Paths.get(Constants.RUNTIME_PATH, Constants.DIRECTORY_DEPLOYMENT,
                Constants.DIRECTORY_WORKSPACE)).toString();
        StringBuilder pathBuilder = new StringBuilder();
        pathBuilder.append(location).append(System.getProperty(FILE_SEPARATOR))
                .append(new String(base64ConfigName));
        return Response.status(Response.Status.OK).entity(workspace.exists(pathBuilder.toString()))
                .type(MediaType.APPLICATION_JSON).build();
    } catch (IOException e) {
        return Response.serverError().entity("failed." + e.getMessage()).build();
    } catch (Throwable ignored) {
        return Response.serverError().entity("failed").build();
    }
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private boolean validKeystoreAlias(String alias, String keystorePassword, String keystoreData,
        String keystoreFileName) throws KeystoreEditorException {
    boolean valid = false;
    try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(keystoreData))) {
        if (StringUtils.isBlank(alias)) {
            throw new IllegalArgumentException("Alias cannot be null.");
        }/*  w ww .  j  a  v  a 2 s  .c o  m*/
        KeyStore ks = null;
        if (StringUtils.endsWithIgnoreCase(keystoreFileName, ".p12")) {
            ks = KeyStore.getInstance("PKCS12");
        } else if (StringUtils.endsWithIgnoreCase(keystoreFileName, ".jks")) {
            ks = KeyStore.getInstance("jks");
        }

        if (ks != null) {
            ks.load(inputStream, keystorePassword.toCharArray());
            valid = ks.containsAlias(alias);
        }
    } catch (Exception e) {
        LOGGER.error("Unable read keystore data.", e);
        throw new KeystoreEditorException("Unable read keystore data.", e);
    }
    return valid;
}

From source file:org.openhab.voice.googletts.internal.GoogleCloudAPI.java

/**
 * Call Google service to synthesize the required text
 *
 * @param text Text to synthesize//from  w  w  w.  j av  a  2  s .c  om
 * @param voice Voice parameter
 * @param audioFormat Audio encoding format
 * @return Audio input stream or {@code null} when encoding exceptions occur
 */
@SuppressWarnings({ "unused", "null" })
private byte[] synthesizeSpeechByGoogle(String text, GoogleTTSVoice voice, String audioFormat)
        throws IOException {
    AudioConfig audioConfig = new AudioConfig(AudioEncoding.valueOf(audioFormat), config.getPitch(),
            config.getSpeakingRate(), config.getVolumeGainDb());
    SynthesisInput synthesisInput = new SynthesisInput(text);
    VoiceSelectionParams voiceSelectionParams = new VoiceSelectionParams(voice.getLocale().getLanguage(),
            voice.getLabel(), SsmlVoiceGender.valueOf(voice.getSsmlGender()));

    SynthesizeSpeechRequest request = new SynthesizeSpeechRequest(audioConfig, synthesisInput,
            voiceSelectionParams);

    HttpRequestBuilder builder = HttpRequestBuilder.postTo(SYTNHESIZE_SPEECH_URL)
            .withHeader(AUTH_HEADER_NAME, getAuthorization())
            .withContent(gson.toJson(request), APPLICATION_JSON);

    SynthesizeSpeechResponse synthesizeSpeechResponse = gson.fromJson(builder.getContentAsString(),
            SynthesizeSpeechResponse.class);

    if (synthesizeSpeechResponse == null) {
        return null;
    }

    byte[] encodedBytes = synthesizeSpeechResponse.getAudioContent().getBytes(StandardCharsets.UTF_8);
    return Base64.getDecoder().decode(encodedBytes);
}

From source file:org.wso2.is.portal.user.client.api.ChallengeQuestionManagerClientServiceImpl.java

public List<ChallengeQuestionSetEntry> getRemainingChallengeQuestions(String userUniqueId)
        throws IdentityRecoveryException, IdentityStoreException, UserNotFoundException {

    if (challengeQuestionManager == null) {
        throw new IdentityRecoveryException("Challenge question manager is not available.");
    }//from   ww  w.j  a  va  2s .  c  o m
    if (realmService == null) {
        throw new IdentityRecoveryException("Realm service is not available.");
    }
    List<ChallengeQuestionSetEntry> challengeQuestionSetEntries = getChallengeQuestionList(userUniqueId);
    List<UserChallengeAnswer> existingAnswers = getChallengeAnswersOfUser(userUniqueId);
    List<String> listofSetIds = new ArrayList<String>();
    for (ChallengeQuestionSetEntry challengeQuestionSetEntry : challengeQuestionSetEntries) {
        listofSetIds.add(challengeQuestionSetEntry.getChallengeQuestionSetId());
    }
    Iterator<UserChallengeAnswer> existingAnswersIterator = existingAnswers.iterator();
    while (existingAnswersIterator.hasNext()) {
        ChallengeQuestion challengeQuestion = existingAnswersIterator.next().getQuestion();
        for (int i = 0; i < listofSetIds.size(); i++) {
            if (StringUtils.equals(challengeQuestion.getQuestionSetId(),
                    new String(Base64.getDecoder().decode(listofSetIds.get(i).getBytes(StandardCharsets.UTF_8)),
                            StandardCharsets.UTF_8))) {
                String setId = listofSetIds.get(i);
                challengeQuestionSetEntries.removeIf(challengeQuestionSetEntry -> StringUtils
                        .equals(challengeQuestionSetEntry.getChallengeQuestionSetId(), setId));
            }
        }

    }
    return challengeQuestionSetEntries;
}

From source file:org.occiware.mart.servlet.impl.ServletEntry.java

/**
 * @param values/*  w w w  .ja  va 2s. c  o m*/
 * @return
 * @throws AuthenticationException
 */
private String parseAuthBasicUsernamePassword(final String values) throws AuthenticationException {

    if (values == null || values.trim().isEmpty()) {
        parseResponseAuthenticationFailed();
        throw (AuthenticationException) occiResponse.getExceptionThrown();
    }

    // Base 64 decode the value string.
    byte[] bval = Base64.getDecoder().decode(values);
    String sval;
    try {
        sval = IOUtils.toString(bval, "UTF-8");

        String[] vals = sval.split(":");

        String username;
        String password;
        username = vals[0];
        if (vals.length <= 1) {
            password = "";
        } else {
            password = vals[1];
        }

        // Check user authorization.
        if (UserManagement.checkBasicUserAuthorisation(username, password)) {
            return username;

        } else {
            parseResponseAuthenticationFailed();
            throw (AuthenticationException) occiResponse.getExceptionThrown();
        }

    } catch (IOException ex) {
        parseResponseAuthenticationFailed();
        throw (AuthenticationException) occiResponse.getExceptionThrown();
    }
}

From source file:org.silverpeas.core.util.StringUtil.java

/**
 * Decodes the specified text with Base64 characters in binary.
 *
 * @param base64Text the text in Base64.
 * @return the binary representation of the text.
 *//*from w w  w .j av a 2  s.c  o m*/
public static byte[] fromBase64(String base64Text) {
    return Base64.getDecoder().decode(base64Text);
}