Example usage for java.io UnsupportedEncodingException getMessage

List of usage examples for java.io UnsupportedEncodingException getMessage

Introduction

In this page you can find the example usage for java.io UnsupportedEncodingException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:be.fedict.eid.dss.protocol.simple.client.SignatureResponseProcessor.java

/**
 * Process the incoming DSS response./*w  w  w  .ja  v  a2 s.co m*/
 * 
 * @param request
 *            the HTTP servlet request that holds the DSS response.
 * @param target
 *            our target URL used for validation of the service signature.
 * @param base64encodedSignatureRequest
 *            optional base64 encoded signature request used for validation
 *            of the service signature. If <code>null</code> meaning
 *            artifact binding was used, signatureRequestId becomes
 *            required.
 * @param signatureRequestId
 *            optional signature request ID case artifact binding was used.
 * @param relayState
 *            optional relayState param
 * @return the signature response DTO.
 * @throws SignatureResponseProcessorException
 *             in case something went wrong.
 */
public SignatureResponse process(HttpServletRequest request, String target,
        String base64encodedSignatureRequest, String signatureRequestId, String relayState)
        throws SignatureResponseProcessorException {
    /*
     * Decode all incoming parameters.
     */
    String signatureStatus = request.getParameter(SIGNATURE_STATUS_PARAMETER);
    if (null == signatureStatus) {
        String msg = SIGNATURE_STATUS_PARAMETER + " parameter not present";
        LOG.error(msg);
        throw new SignatureResponseProcessorException(msg);
    }
    LOG.debug("signature status: " + signatureStatus);
    if (!"OK".equals(signatureStatus)) {
        String msg = "invalid signature status: " + signatureStatus;
        LOG.error(msg);
        if ("USER_CANCELLED".equals(signatureStatus)) {
            throw new UserCancelledSignatureResponseProcessorException("user cancelled");
        }
        throw new SignatureResponseProcessorException(msg);
    }

    String signatureResponse = request.getParameter(SIGNATURE_RESPONSE_PARAMETER);
    String signatureResponseId = request.getParameter(SIGNATURE_RESPONSE_ID_PARAMETER);

    if (null == signatureResponse && null == signatureResponseId) {
        String msg = "No " + SIGNATURE_RESPONSE_PARAMETER + " or " + SIGNATURE_RESPONSE_ID_PARAMETER
                + " parameter found!";
        LOG.error(msg);
        throw new SignatureResponseProcessorException(msg);
    }

    String encodedSignatureCertificate = request.getParameter(SIGNATURE_CERTIFICATE_PARAMETER);
    if (null == encodedSignatureCertificate) {
        String msg = SIGNATURE_CERTIFICATE_PARAMETER + " parameter not present";
        LOG.error(msg);
        throw new SignatureResponseProcessorException(msg);
    }

    /*
     * Validate RelayState if needed.
     */
    String responseRelayState = request.getParameter(RELAY_STATE_PARAMETER);
    if (null != relayState) {
        if (!relayState.equals(responseRelayState)) {
            String msg = "Returned relayState \"" + responseRelayState + "\" "
                    + "does not match expected RelayState: \"" + relayState + "\"";
            LOG.error(msg);
            throw new SignatureResponseProcessorException(msg);
        }
    }

    /*
     * Check service signature.
     */
    String encodedServiceSigned = request.getParameter(SERVICE_SIGNED_PARAMETER);
    if (null != encodedServiceSigned) {
        LOG.debug("service signature present");
        String serviceSigned;
        try {
            serviceSigned = URLDecoder.decode(encodedServiceSigned, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new SignatureResponseProcessorException("URL decoder error: " + e.getMessage());
        }
        String encodedServiceSignature = request.getParameter(SERVICE_SIGNATURE_PARAMETER);
        if (null == encodedServiceSignature) {
            throw new SignatureResponseProcessorException("missing " + SERVICE_SIGNATURE_PARAMETER);
        }
        byte[] serviceSignatureValue = Base64.decode(encodedServiceSignature);

        /*
         * Parse the service certificate chain.
         */
        int serviceCertificateChainSize = Integer
                .parseInt(request.getParameter(SERVICE_CERTIFICATE_CHAIN_SIZE_PARAMETER));
        List<X509Certificate> serviceCertificateChain = new LinkedList<X509Certificate>();
        for (int idx = 1; idx <= serviceCertificateChainSize; idx++) {
            String encodedCertificate = request.getParameter(SERVICE_CERTIFICATE_PARAMETER_PREFIX + idx);
            byte[] certificateData = Base64.decode(encodedCertificate);
            X509Certificate certificate;
            try {
                certificate = (X509Certificate) this.certificateFactory
                        .generateCertificate(new ByteArrayInputStream(certificateData));
            } catch (CertificateException e) {
                throw new SignatureResponseProcessorException("cert decoding error: " + e.getMessage());
            }
            serviceCertificateChain.add(certificate);
        }

        if (null == target) {
            throw new SignatureResponseProcessorException(
                    "target parameter required for validation of service signature");
        }

        if (null == base64encodedSignatureRequest && null == signatureRequestId) {
            throw new SignatureResponseProcessorException("base64encodedSignatureRequest or signatureRequestId "
                    + "required for validation of service signature");
        }
        try {
            verifyServiceSignature(serviceSigned, target, base64encodedSignatureRequest, signatureRequestId,
                    signatureResponse, signatureResponseId, encodedSignatureCertificate, serviceSignatureValue,
                    serviceCertificateChain);
        } catch (Exception e) {
            String msg = "service signature invalid: " + e.getMessage();
            LOG.error(msg, e);
            throw new SignatureResponseProcessorException(msg);
        }
    } else {
        if (null != this.serviceFingerprint) {
            /*
             * In case of a service fingerprint being available, we really
             * require the eID DSS to send us a service signature.
             */
            throw new SignatureResponseProcessorException(
                    "Service fingerprint available but service signature is missing");
        }
    }

    /*
     * Parse all incoming data.
     */
    byte[] decodedSignatureResponse = null;
    if (null != signatureResponse) {
        decodedSignatureResponse = Base64.decode(signatureResponse);
        LOG.debug("decoded signature response size: " + decodedSignatureResponse.length);
    }

    byte[] decodedSignatureCertificate = Base64.decode(encodedSignatureCertificate);
    X509Certificate signatureCertificate;
    try {
        signatureCertificate = (X509Certificate) this.certificateFactory
                .generateCertificate(new ByteArrayInputStream(decodedSignatureCertificate));
    } catch (CertificateException e) {
        String msg = SIGNATURE_CERTIFICATE_PARAMETER + " is not an X509 certificate";
        LOG.error(msg, e);
        throw new SignatureResponseProcessorException(msg);
    }

    /*
     * Construct result DTO.
     */
    return new SignatureResponse(decodedSignatureResponse, signatureResponseId, signatureCertificate);
}

From source file:com.taikang.dic.ltci.service.impl.AgencyInterfaceServiceImpl.java

/**
 * ??mq?->? mq?//  w ww .jav  a 2s  .  com
 *
 * @author itw_muwg
 */
@RabbitListener(queues = "${ltci.orgApplication.queue}")
@Override
public void getorgApplication(byte[] bytes) {
    logger.debug("=======ReconsiderServiceImpl getReconsiderReceive=========");
    String message = null;
    try {
        message = new String(bytes, systemCharset);
    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage(), e);
        return;
    }
    logger.info("=======mq " + orgApplicationQueueName + "???=========");
    //?
    parseMessage(message);
}

From source file:de.weltraumschaf.groundzero.transform.ReportReader.java

/**
 * Read and parses the XML from file and returns a report model object.
 *
 * @param input must not be {@code null}
 * @param inputEncoding must not be {@code null} or empty
 * @return may return {@code null}/*from  w  ww .  j a v  a 2 s . co  m*/
 * @throws UnsupportedInputEncodingException if unsupported encoding is used
 * @throws XmlInputParseException if SAX handler throws a parse exception
 * @throws XmlInputFileReadException if input file can't be read
 */
public CheckstyleReport read(final File input, final String inputEncoding)
        throws UnsupportedInputEncodingException, XmlInputParseException, XmlInputFileReadException {
    Validate.notNull(input);

    try (final InputStream inputStream = new FileInputStream(input)) {
        final Reader reader = new InputStreamReader(inputStream, inputEncoding);
        xmlReader.parse(new InputSource(reader));
    } catch (final UnsupportedEncodingException ex) {
        throw new UnsupportedInputEncodingException(
                String.format("ERROR: Unsuported input encoding '%s'!", inputEncoding), ex);
    } catch (final SAXException ex) {
        throw new XmlInputParseException(
                String.format("ERROR: Excpetion thrown while parsing input file '%s'! %s",
                        input.getAbsolutePath(), ex.getMessage()),
                ex);
    } catch (final IOException ex) {
        throw new XmlInputFileReadException(
                String.format("ERROR: Excpetion thrown while reading input file '%s'! %s",
                        input.getAbsolutePath(), ex.getMessage()),
                ex);
    }

    return handler.getReport();
}

From source file:com.fujitsu.dc.test.jersey.DcRestAdapter.java

/**
 * PUT?????./*from  w  ww. j  a v  a2s  .  c  o m*/
 * @param url ?URL
 * @param data PUT?
 * @param contentType 
 * @return HttpPut
 * @throws DcException DAO
 */
protected final HttpPut makePutRequest(final String url, final String data, final String contentType)
        throws DcException {
    HttpPut request = new HttpPut(url);
    HttpEntity body = null;
    try {
        if (DcRestAdapter.CONTENT_TYPE_JSON.equals(contentType)) {
            String bodyStr = toUniversalCharacterNames(data);
            body = new StringEntity(bodyStr);
        } else {
            body = new StringEntity(data, DcRestAdapter.ENCODE);
        }
    } catch (UnsupportedEncodingException e) {
        throw DcException.create("error while request body encoding : " + e.getMessage(), 0);
    }
    request.setEntity(body);
    return request;
}

From source file:de.thm.arsnova.services.UserService.java

public void sendActivationEmail(DbUser dbUser) {
    String activationUrl;//from www.j av a  2  s .  co m
    try {
        activationUrl = MessageFormat.format("{0}{1}/{2}?action=activate&username={3}&key={4}", rootUrl,
                customizationPath, activationPath, UriUtils.encodeQueryParam(dbUser.getUsername(), "UTF-8"),
                dbUser.getActivationKey());
    } catch (UnsupportedEncodingException e1) {
        LOGGER.error(e1.getMessage());

        return;
    }

    sendEmail(dbUser, regMailSubject, MessageFormat.format(regMailBody, activationUrl));
}

From source file:org.commonjava.rwx.http.httpclient4.HC4SyncEStreamClient.java

@Override
public List<Event<?>> call(final EventStreamGenerator requestGenerator, final boolean expectVoidResponse,
        UrlBuilder urlBuilder, RequestModifier requestModifier) throws XmlRpcException {
    final List<Event<?>> events = requestGenerator.getEvents();

    final String methodName = getRequestMethod(events);
    if (methodName == null) {
        throw new XmlRpcTransportException("Request value is not annotated with @Request.", events);
    }/* www  .  jav a2  s.  co m*/

    Logger logger = LoggerFactory.getLogger(getClass());
    final HttpPost method;
    try {
        String url = UrlUtils.buildUrl(siteConfig.getUri(), extraPath);
        if (urlBuilder != null) {
            url = urlBuilder.buildUrl(url).throwError().get();
        }

        method = new HttpPost(url);
        method.setHeader("Content-Type", "text/xml");

        if (requestModifier != null) {
            requestModifier.modifyRequest(method);
        }

        // TODO: Can't we get around pre-rendering to string?? Maybe not, if we want content-length to be right...
        final JDomRenderer renderer = new JDomRenderer();
        requestGenerator.generate(renderer);

        final String content = renderer.documentToString();
        logger.trace("Sending request:\n\n" + content + "\n\n");

        method.setEntity(new StringEntity(content));
    } catch (final UnsupportedEncodingException e) {
        throw new XmlRpcTransportException("Call failed: " + methodName, events, e);
    } catch (MalformedURLException e) {
        throw new XmlRpcTransportException("Failed to construct URL from: %s and extra-path: %s. Reason: %s", e,
                siteConfig.getUri(), Arrays.asList(extraPath), e.getMessage());
    }

    CloseableHttpClient client = null;
    try {
        client = httpFactory.createClient(siteConfig);

        if (expectVoidResponse) {
            final EStreamResponseHandler handler = new EStreamResponseHandler();
            client.execute(method, handler);

            handler.throwExceptions();
            return null;
        } else {
            final EStreamResponseHandler handler = new EStreamResponseHandler();
            final List<Event<?>> responseEvents = client.execute(method, handler);

            handler.throwExceptions();
            return responseEvents;
        }
    } catch (final ClientProtocolException e) {
        throw new XmlRpcTransportException("Call failed: " + methodName, events, e);
    } catch (final IOException e) {
        throw new XmlRpcTransportException("Call failed: " + methodName, events, e);
    } catch (JHttpCException e) {
        throw new XmlRpcTransportException("Call failed: " + methodName, events, e);
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:org.commonjava.rwx.http.httpclient4.HC4SyncObjectClient.java

@Override
public <T> T call(final Object request, final Class<T> responseType, final UrlBuilder urlBuilder,
        final RequestModifier requestModifier) throws XmlRpcException {
    final String methodName = getRequestMethod(request);
    if (methodName == null) {
        throw new XmlRpcTransportException("Request value is not annotated with @Request.", request);
    }//from ww w .  j a v  a  2  s . co  m

    final HttpPost method;
    try {
        Logger logger = LoggerFactory.getLogger(getClass());

        String url = UrlUtils.buildUrl(siteConfig.getUri(), extraPath);
        logger.trace("Unadorned URL: '{}'", url);

        if (urlBuilder != null) {
            UrlBuildResult buildResult = urlBuilder.buildUrl(url);
            logger.trace("UrlBuilder ({}) result: {}", urlBuilder.getClass().getName(), buildResult);
            url = buildResult.throwError().get();
        }

        logger.trace("POSTing {} request to: '{}'", methodName, url);

        method = new HttpPost(url);
        method.setHeader("Content-Type", "text/xml");

        if (requestModifier != null) {
            requestModifier.modifyRequest(method);
        }

        // TODO: Can't we get around pre-rendering to string?? Maybe not, if we want content-length to be right...
        final String content = bindery.renderString(request);

        logger.trace("Sending request:\n\n" + content + "\n\n");

        method.setEntity(new StringEntity(content));
    } catch (final UnsupportedEncodingException e) {
        throw new XmlRpcTransportException("Call failed: " + methodName, request, e);
    } catch (MalformedURLException e) {
        throw new XmlRpcTransportException("Failed to construct URL from: %s and extra-path: %s. Reason: %s", e,
                siteConfig.getUri(), Arrays.asList(extraPath), e.getMessage());
    }

    CloseableHttpClient client = null;
    try {
        client = httpFactory.createClient(siteConfig);

        if (Void.class.equals(responseType)) {
            final ObjectResponseHandler<VoidResponse> handler = new ObjectResponseHandler<VoidResponse>(bindery,
                    VoidResponse.class);
            client.execute(method, handler);

            handler.throwExceptions();
            return null;
        } else {
            final ObjectResponseHandler<T> handler = new ObjectResponseHandler<T>(bindery, responseType);
            final T response = client.execute(method, handler);

            handler.throwExceptions();
            return response;

        }
    } catch (final ClientProtocolException e) {
        throw new XmlRpcTransportException("Call failed: " + methodName, request, e);
    } catch (final IOException e) {
        throw new XmlRpcTransportException("Call failed: " + methodName, request, e);
    } catch (JHttpCException e) {
        throw new XmlRpcTransportException("Call failed: " + methodName, request, e);
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:com.fluidops.iwb.api.RequestMapperImpl.java

@Override
public String normalize(String name) {
    name = name.replaceAll(" ", "_");

    try {/* w w w . ja  v a2 s .c om*/
        name = URLEncoder.encode(name, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage(), e);
    }

    return name;
}

From source file:edu.lternet.pasta.doi.EzidRegistrar.java

/**
 * Make the DOI obsolete by setting the EZID metadata field "_status" to
 * "unavailable".//  ww w  .j  av a2  s . c om
 * 
 * @param doi The DOI to obsolete
 * @throws EzidException
 */
public void obsoleteDoi(String doi) throws EzidException {

    HttpHost httpHost = new HttpHost(this.host, Integer.valueOf(this.port), this.protocol);
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    AuthScope authScope = new AuthScope(httpHost.getHostName(), httpHost.getPort());
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.ezidUser, this.ezidPassword);
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(authScope, credentials);

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();

    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(httpHost, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);

    String url = this.getEzidUrl("/id/" + doi);

    StringBuffer metadata = new StringBuffer("");
    metadata.append("_status: unavailable | withdrawn by author\n");

    HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader("Content-type", "text/plain");
    HttpEntity stringEntity = null;
    Integer statusCode = null;
    String entityString = null;

    try {
        stringEntity = new StringEntity(metadata.toString());
        httpPost.setEntity(stringEntity);
        HttpResponse httpResponse = httpClient.execute(httpHost, httpPost, context);
        statusCode = httpResponse.getStatusLine().getStatusCode();
        HttpEntity httpEntity = httpResponse.getEntity();
        entityString = EntityUtils.toString(httpEntity);
    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } finally {
        closeHttpClient(httpClient);
    }

    logger.info("obsoleteDoi: " + entityString);

    if (statusCode != HttpStatus.SC_OK) {
        String gripe = "DOI obsoletion failed for: " + doi;
        throw new EzidException(gripe);
    }

}

From source file:io.personium.test.jersey.PersoniumRestAdapter.java

/**
 * POST?????./*  w  ww . jav a 2s. c o m*/
 * @param url POST?URL
 * @param data POST?
 * @param contentType 
 * @return POST??
 * @throws PersoniumException DAO
 */
protected final HttpPost makePostRequest(final String url, final String data, final String contentType)
        throws PersoniumException {
    HttpPost request = new HttpPost(url);
    HttpEntity body = null;
    try {
        String bodyStr = toUniversalCharacterNames(data);
        body = new StringEntity(bodyStr);
    } catch (UnsupportedEncodingException e) {
        throw PersoniumException.create("error while request body encoding : " + e.getMessage(), 0);
    }
    request.setEntity(body);
    makeCommonHeaders(request, contentType, contentType, null);
    return request;
}