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.applet.service.signer.asic.ASiCURIDereferencer.java

public Data dereference(URIReference uriReference, XMLCryptoContext context) throws URIReferenceException {
    if (null == uriReference) {
        throw new URIReferenceException("URIReference cannot be null");
    }//from w  w  w.j  a va  2s .  c  o m
    if (null == context) {
        throw new URIReferenceException("XMLCrytoContext cannot be null");
    }

    String uri = uriReference.getURI();
    try {
        uri = URLDecoder.decode(uri, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        LOG.warn("could not URL decode the uri: " + uri);
    }
    LOG.debug("dereference: " + uri);

    InputStream zipInputStream;
    if (null != this.tmpFile) {
        try {
            zipInputStream = new FileInputStream(this.tmpFile);
        } catch (FileNotFoundException e) {
            throw new URIReferenceException("file not found error: " + e.getMessage(), e);
        }
    } else {
        zipInputStream = new ByteArrayInputStream(this.data);
    }
    InputStream dataInputStream;
    try {
        dataInputStream = ODFUtil.findDataInputStream(zipInputStream, uri);
    } catch (IOException e) {
        throw new URIReferenceException("I/O error: " + e.getMessage(), e);
    }
    if (null == dataInputStream) {
        return this.baseUriDereferener.dereference(uriReference, context);
    }
    return new OctetStreamData(dataInputStream, uri, null);
}

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

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

From source file:com.mirth.connect.connectors.tcp.TcpMessageDispatcher.java

public void manageResponseAck(StateAwareSocket socket, String endpointUri, MessageObject messageObject) {
    int maxTime = connector.getAckTimeout();
    if (maxTime <= 0) { // TODO: Either make a UI setting to "not check for
        // ACK" or document this
        // We aren't waiting for an ACK
        messageObjectController.setSuccess(messageObject, "Message successfully sent", null);
        return;//from w  w  w  .j  av a2 s  .co m
    }
    byte[] theAck = getAck(socket, endpointUri);

    if (theAck == null) {
        // NACK
        messageObjectController.setSuccess(messageObject, "Empty Response", null);
        return;
    }
    try {
        String ackString = new String(theAck, connector.getCharsetEncoding());
        if (connector.getReplyChannelId() != null & !connector.getReplyChannelId().equals("")
                && !connector.getReplyChannelId().equals("sink")) {
            // reply back to channel
            VMRouter router = new VMRouter();
            router.routeMessageByChannelId(connector.getReplyChannelId(), ackString, true);
        }
        messageObjectController.setSuccess(messageObject, ackString, null);
    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage());
        messageObjectController.setError(messageObject, Constants.ERROR_411,
                "Error setting encoding: " + connector.getCharsetEncoding(), e, null);
        alertController.sendAlerts(((TcpConnector) connector).getChannelId(), Constants.ERROR_411,
                "Error setting encoding: " + connector.getCharsetEncoding(), e);
    }
}

From source file:eu.planets_project.pp.plato.action.workflow.CreateExecutablePlanAction.java

public void downloadExecutablePlan() {

    if (selectedPlan.getRecommendation().getAlternative() == null
            || selectedPlan.getRecommendation().getAlternative().getAction() == null) {
        return;//  ww  w .j a va 2s .  com
    }

    byte[] plan;
    try {
        plan = selectedPlan.getExecutablePlanDefinition().getExecutablePlan().getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR, "Unsupported encoding. " + e.getMessage());
        return;
    }

    if (plan != null) {
        Downloader.instance().download(plan, "executable-preservation-plan.xml", "text/xml");
    }
}

From source file:eu.planets_project.pp.plato.action.workflow.CreateExecutablePlanAction.java

public void downloadEprintsExecutablePlan() {

    if (selectedPlan.getRecommendation().getAlternative() == null
            || selectedPlan.getRecommendation().getAlternative().getAction() == null) {
        return;//from   w  ww  .ja v  a  2s. c om
    }

    byte[] plan;
    try {
        plan = selectedPlan.getExecutablePlanDefinition().getEprintsExecutablePlan().getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        FacesMessages.instance().add(FacesMessage.SEVERITY_ERROR, "Unsupported encoding. " + e.getMessage());
        return;
    }

    if (plan != null) {
        Downloader.instance().download(plan, "executable-preservation-plan.xml", "text/xml");
    }
}

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

@Override
public void initiatePasswordReset(String username) {
    DbUser dbUser = databaseDao.getUser(username);
    if (null == dbUser) {
        throw new NotFoundException();
    }/*from w  w w  .  j a  v  a 2s  .co m*/
    if (System.currentTimeMillis() < dbUser.getPasswordResetTime() + REPEATED_PASSWORD_RESET_DELAY_MS) {
        throw new BadRequestException();
    }

    dbUser.setPasswordResetKey(RandomStringUtils.randomAlphanumeric(32));
    dbUser.setPasswordResetTime(System.currentTimeMillis());
    databaseDao.createOrUpdateUser(dbUser);

    String resetPasswordUrl;
    try {
        resetPasswordUrl = MessageFormat.format("{0}{1}/{2}?action=resetpassword&username={3}&key={4}", rootUrl,
                customizationPath, resetPasswordPath, UriUtils.encodeQueryParam(dbUser.getUsername(), "UTF-8"),
                dbUser.getPasswordResetKey());
    } catch (UnsupportedEncodingException e1) {
        LOGGER.error(e1.getMessage());

        return;
    }

    sendEmail(dbUser, resetPasswordMailSubject, MessageFormat.format(resetPasswordMailBody, resetPasswordUrl));
}

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

/**
 * GET/POST/PUT/DELETE ?./*from  www  . jav a  2  s.c o  m*/
 * @param method Http
 * @param url URL
 * @param body 
 * @param headers ??
 * @return DcResponse
 * @throws DcException DAO
 */
public DcResponse request(final String method, String url, String body, HashMap<String, String> headers)
        throws DcException {
    HttpEntityEnclosingRequestBase req = new HttpEntityEnclosingRequestBase() {
        @Override
        public String getMethod() {
            return method;
        }
    };
    req.setURI(URI.create(url));
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        req.setHeader(entry.getKey(), entry.getValue());
    }
    req.addHeader("X-Dc-Version", DcCoreTestConfig.getCoreVersion());

    if (body != null) {
        HttpEntity httpEntity = null;
        try {
            String bodyStr = toUniversalCharacterNames(body);
            httpEntity = new StringEntity(bodyStr);
        } catch (UnsupportedEncodingException e) {
            throw DcException.create("error while request body encoding : " + e.getMessage(), 0);
        }
        req.setEntity(httpEntity);
    }
    debugHttpRequest(req, body);
    return this.request(req);
}

From source file:ti.modules.titanium.geolocation.GeolocationModule.java

private String buildGeoURL(String direction, String mid, String aguid, String sid, String query,
        String countryCode) {/*from  w ww. j  ava  2  s.c  om*/
    String url = null;
    try {
        StringBuilder sb = new StringBuilder();

        sb.append(BASE_GEO_URL).append("d=r").append("&mid=").append(mid).append("&aguid=").append(aguid)
                .append("&sid=").append(sid).append("&q=").append(URLEncoder.encode(query, "utf-8"))
        // .append("&c=").append(countryCode)
        ;
        // d=%@&mid=%@&aguid=%@&sid=%@&q=%@&c=%@",direction,mid,aguid,sid,[address
        // stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],countryCode];

        url = sb.toString();
    } catch (UnsupportedEncodingException e) {
        Log.w(LCAT, "Unable to encode query to utf-8: " + e.getMessage());
    }

    return url;
}

From source file:com.redhat.red.build.koji.http.httpclient4.HC4SyncObjectClient.java

private <T> T doCall(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);
    }// www.jav  a2s  .  com

    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);
        }

        final String content = new RWXMapper().render(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>(
                    VoidResponse.class);
            client.execute(method, handler);

            handler.throwExceptions();
            return null;
        } else {
            final ObjectResponseHandler<T> handler = new ObjectResponseHandler<T>(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:edu.lternet.pasta.doi.EzidRegistrar.java

/**
 * Registers the resource DOI based on the DataCite metadata object.
 * /*from  w w  w .  jav  a  2s  .c o  m*/
 * @throws EzidException
 */
public void registerDataCiteMetadata() throws EzidException {

    if (this.dataCiteMetadata == null) {
        String gripe = "registerDataCiteMetadata: DataCite metadata object is null.";
        throw new EzidException(gripe);
    }

    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 doi = this.dataCiteMetadata.getDigitalObjectIdentifier().getDoi();
    String url = this.getEzidUrl("/id/" + doi);
    StringBuffer metadata = new StringBuffer("");
    metadata.append("datacite: " + this.dataCiteMetadata.toDataCiteXml() + "\n");
    metadata.append("_target: " + this.dataCiteMetadata.getLocationUrl() + "\n");
    HttpPut httpPut = new HttpPut(url);
    httpPut.setHeader("Content-type", "text/plain");
    HttpEntity stringEntity = null;
    Integer statusCode = null;
    String entityString = null;

    try {
        stringEntity = new StringEntity(metadata.toString());
        httpPut.setEntity(stringEntity);
        HttpResponse httpResponse = httpClient.execute(httpHost, httpPut, 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("registerDataCiteMetadata: " + this.dataCiteMetadata.getLocationUrl() + "\n" + entityString);

    // Test for DOI collision or DOI registration failure
    if ((statusCode == HttpStatus.SC_BAD_REQUEST) && (entityString != null)
            && (entityString.contains("identifier already exists"))) {
        String gripe = "identifier already exists";
        throw new EzidException(gripe);
    } else if (statusCode != HttpStatus.SC_CREATED) {
        logger.error(this.dataCiteMetadata.toDataCiteXml());
        String gripe = "DOI registration failed for: " + doi;
        throw new EzidException(gripe);
    }

}