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:org.guanxi.sp.engine.service.saml2.SAML2ProfileService.java

/** @see org.guanxi.sp.engine.service.generic.ProfileService#doProfile(javax.servlet.http.HttpServletRequest, String, String, org.guanxi.xal.saml2.metadata.GuardRoleDescriptorExtensions, String, org.guanxi.common.entity.EntityFarm) */
public ModelAndView doProfile(HttpServletRequest request, String guardID, String guardSessionID,
        GuardRoleDescriptorExtensions guardNativeMetadata, String entityID, EntityFarm farm)
        throws GuanxiException {
    ModelAndView mAndV = new ModelAndView();

    String relayState = guardSessionID.replaceAll("GUARD", "ENGINE");

    // Load the metadata for the IdP
    EntityManager manager = farm.getEntityManagerForID(entityID);
    if (manager == null) {
        logger.error("Could not find manager for IdP '" + entityID);
        throw new GuanxiException("Could not find manager for IdP " + entityID);
    }// ww w  .j  a va2 s .c  o  m
    Metadata entityMetadata = manager.getMetadata(entityID);
    if (entityMetadata == null) {
        logger.error("Could not find manager for IdP " + entityID);
        throw new GuanxiException("Could not find metadata for IdP " + entityID);
    }
    EntityDescriptorType saml2Metadata = (EntityDescriptorType) entityMetadata.getPrivateData();

    String wbssoURL = null;
    String binding = null;
    EndpointType[] ssos = saml2Metadata.getIDPSSODescriptorArray(0).getSingleSignOnServiceArray();
    for (EndpointType sso : ssos) {
        if ((sso.getBinding().equalsIgnoreCase(SAML.SAML2_BINDING_HTTP_POST))
                || (sso.getBinding().equalsIgnoreCase(SAML.SAML2_BINDING_HTTP_REDIRECT))) {
            wbssoURL = sso.getLocation();
            if (sso.getBinding().equalsIgnoreCase(SAML.SAML2_BINDING_HTTP_POST))
                binding = SAML.SAML2_BINDING_HTTP_POST;
            else if (sso.getBinding().equalsIgnoreCase(SAML.SAML2_BINDING_HTTP_REDIRECT))
                binding = SAML.SAML2_BINDING_HTTP_REDIRECT;
            break;
        }
    }
    if (wbssoURL == null) {
        logger.error("IdP does not support WBSSO " + entityID);
        throw new GuanxiException("IdP does not support WBSSO " + entityID);
    }

    // Create an AuthnRequest
    AuthnRequestDocument authnRequestDoc = AuthnRequestDocument.Factory.newInstance();
    AuthnRequestType authnRequest = authnRequestDoc.addNewAuthnRequest();
    authnRequest.setID(Utils.createNCNameID());
    authnRequest.setVersion("2.0");
    authnRequest.setIssueInstant(Calendar.getInstance());
    Utils.zuluXmlObject(authnRequest, 0);
    NameIDType issuer = NameIDType.Factory.newInstance();
    issuer.setStringValue(guardID);
    authnRequest.setIssuer(issuer);
    authnRequest.setAssertionConsumerServiceURL(assertionConsumerServiceURL);
    authnRequest.setProtocolBinding(SAML.SAML2_BINDING_HTTP_POST);
    // Only if signed
    //authnRequest.setDestination("https://sgarbh.smo.uhi.ac.uk:8443/idp/profile/SAML2/POST/SSO");

    // Sort out the namespaces for saving the Response
    HashMap<String, String> namespaces = new HashMap<String, String>();
    namespaces.put(SAML.NS_SAML_20_PROTOCOL, SAML.NS_PREFIX_SAML_20_PROTOCOL);
    namespaces.put(SAML.NS_SAML_20_ASSERTION, SAML.NS_PREFIX_SAML_20_ASSERTION);

    XmlOptions xmlOptions = new XmlOptions();
    xmlOptions.setSavePrettyPrint();
    xmlOptions.setSavePrettyPrintIndent(2);
    xmlOptions.setUseDefaultNamespace();
    xmlOptions.setSaveAggressiveNamespaces();
    xmlOptions.setSaveSuggestedPrefixes(namespaces);
    xmlOptions.setSaveNamespacesFirst();

    // Get the config ready for signing
    SecUtilsConfig secUtilsConfig = new SecUtilsConfig();
    secUtilsConfig.setKeystoreFile(guardNativeMetadata.getKeystore());
    secUtilsConfig.setKeystorePass(guardNativeMetadata.getKeystorePassword());
    secUtilsConfig.setKeystoreType("JKS");
    secUtilsConfig.setPrivateKeyAlias(guardID);
    secUtilsConfig.setPrivateKeyPass(guardNativeMetadata.getKeystorePassword());
    secUtilsConfig.setCertificateAlias(guardID);

    // Break out to DOM land to get the SAML Response signed...
    /*
    Document signedDoc = null;
    try {
      // Need to use newDomNode to preserve namespace information
      signedDoc = SecUtils.getInstance().sign(secUtilsConfig, (Document)authnRequestDoc.newDomNode(xmlOptions), "");
      // ...and go back to XMLBeans land when it's ready
      authnRequestDoc = AuthnRequestDocument.Factory.parse(signedDoc);
    }
    catch(GuanxiException ge) {
      logger.error("Could not sign AuthnRequest", ge);
      mAndV.setViewName(errorView);
      mAndV.getModel().put(errorViewDisplayVar, messages.getMessage("engine.error.could.not.sign.message",
                                                            null, request.getLocale()));
      return mAndV;
    }
    catch(XmlException xe) {
      logger.error("Couldn't convert signed AuthnRequest back to XMLBeans", xe);
      mAndV.setViewName(errorView);
      mAndV.getModel().put(errorViewDisplayVar, messages.getMessage("engine.error.could.not.sign.message",
                                                            null, request.getLocale()));
      return mAndV;
    }
    */

    // Base 64 encode the AuthnRequest
    //String authnRequestB64 = Utils.base64(signedDoc);
    //String authnRequestB64 = Utils.base64((Document)authnRequestDoc.newDomNode(xmlOptions));

    // Do the profile quickstep
    String authnRequestForIdP = null;
    if (binding.equals(SAML.SAML2_BINDING_HTTP_REDIRECT)) {
        mAndV.setViewName(httpRedirectView);
        String deflatedRequest = Utils.deflate(authnRequestDoc.toString(),
                Utils.RFC1951_DEFAULT_COMPRESSION_LEVEL, Utils.RFC1951_NO_WRAP);
        authnRequestForIdP = Utils.base64(deflatedRequest.getBytes());
        authnRequestForIdP = authnRequestForIdP.replaceAll(System.getProperty("line.separator"), "");
        try {
            authnRequestForIdP = URLEncoder.encode(authnRequestForIdP, "UTF-8");
            relayState = URLEncoder.encode(relayState, "UTF-8");
        } catch (UnsupportedEncodingException uee) {
            logger.error("couldn't encode SAMLRequest");
            throw new GuanxiException("couldn't encode SAMLRequest: " + uee.getMessage());
        }
    } else if (binding.equals(SAML.SAML2_BINDING_HTTP_POST)) {
        mAndV.setViewName(httpPOSTView);
        authnRequestForIdP = Utils.base64(authnRequestDoc.toString().getBytes());
    }

    // Send the AuthnRequest to the IdP
    mAndV.getModel().put("SAMLRequest", authnRequestForIdP);
    mAndV.getModel().put("RelayState", relayState);
    mAndV.getModel().put("wbsso_endpoint", wbssoURL);
    return mAndV;
}

From source file:dev.meng.wikidata.pageview.Consolidator.java

private Map<String, String>[] queryPageIdsBatchWorker(String lang, String titles, String cont) {
    Map<String, Object> params = new HashMap<>();
    params.put("format", "json");
    params.put("action", "query");
    params.put("titles", titles);
    params.put("prop", "info");
    if (cont != null) {
        params.put("incontinue", cont);
    }//from   w w w  . j a v a2  s . c o  m

    Map<String, String> norm = new HashMap<>();
    Map<String, String> result = new HashMap<>();

    try {
        String urlString = String.format(Configure.PAGEVIEW.API_ENDPOINT, lang) + "?"
                + StringUtils.mapToURLParameters(params, Configure.PAGEVIEW.DEFAULT_ENCODING);
        URL url = new URL(urlString);

        JSONObject response = HttpUtils.queryForJSONResponse(url, Configure.FILEUSAGE.DEFAULT_ENCODING);

        if (response != null && response.has("query")) {
            JSONObject responseQuery = response.getJSONObject("query");
            if (responseQuery.has("normalized")) {
                JSONArray normalizations = responseQuery.getJSONArray("normalized");
                for (int i = 0; i < normalizations.length(); i++) {
                    JSONObject normalization = normalizations.getJSONObject(i);
                    norm.put(normalization.getString("from"), normalization.getString("to"));
                }
            }
            if (responseQuery.has("pages")) {
                JSONObject pages = responseQuery.getJSONObject("pages");
                for (String pageKey : (Set<String>) pages.keySet()) {
                    if (Long.parseLong(pageKey) > 0) {
                        JSONObject page = pages.getJSONObject(pageKey);
                        if (page.has("ns") && page.getLong("ns") == 0L) {
                            result.put(page.getString("title"), Long.toString(page.getLong("pageid")));
                        }
                    }
                }
            }

            String queryContinue = null;
            if (response.has("query-continue")) {
                queryContinue = response.getJSONObject("query-continue").getJSONObject("info")
                        .getString("incontinue");
            }

            if (queryContinue != null) {
                Map<String, String>[] moreResult = queryPageIdsBatchWorker(lang, titles, queryContinue);
                norm.putAll(moreResult[0]);
                result.putAll(moreResult[1]);
            }
        }
    } catch (UnsupportedEncodingException ex) {
        Logger.log(this.getClass(), LogLevel.WARNING,
                "Error in encoding: " + params.toString() + ", " + ex.getMessage());
    } catch (MalformedURLException ex) {
        Logger.log(this.getClass(), LogLevel.ERROR, ex);
    } catch (IOException ex) {
        Logger.log(this.getClass(), LogLevel.ERROR, ex);
    } catch (StringConvertionException ex) {
        Logger.log(this.getClass(), LogLevel.ERROR, ex);
    }

    return new Map[] { norm, result };
}

From source file:net.sourceforge.fenixedu.domain.accounting.events.export.SIBSOutgoingPaymentFile.java

public SIBSOutgoingPaymentFile(DateTime lastSuccessfulSentDateTime) {
    super();/*from  w  w w.  jav a2  s.  c  o  m*/
    setExecutionYear(subjectExecutionYear());

    try {
        StringBuilder errorsBuilder = new StringBuilder();
        byte[] paymentFileContents = createPaymentFile(lastSuccessfulSentDateTime, errorsBuilder)
                .getBytes("ASCII");
        setErrors(errorsBuilder.toString());
        init(outgoingFilename(), outgoingFilename(), paymentFileContents, RoleGroup.get(RoleType.MANAGER));
    } catch (UnsupportedEncodingException e) {
        throw new DomainException(e.getMessage(), e);
    }
}

From source file:com.threewks.thundr.http.SyntheticHttpServletResponse.java

/**
 * Returns the content sent in this synthetic response. The content interprets the underlying bytes written to the response using the specified character encoding.
 * /*  ww w  .  j a  va  2 s  .  c om*/
 * @return
 */
public String getOutput() {
    try {
        return getResponseContentInternal().toString(characterEncoding);
    } catch (UnsupportedEncodingException e) {
        throw new BaseException(e,
                "Failed to get output, this platform does not support the specified character encoding '%s': %s",
                characterEncoding, e.getMessage());
    }
}

From source file:com.sitexa.android.data.net.volley.VolleyApi.java

protected Observable<ApiResult> doGet(final String doAction, final Map<String, String> requestParam,
        final boolean shouldCache, final boolean refreshCache, final boolean checkNetwork) {
    final ApiResult result = new ApiResult();

    return Observable.create(new Observable.OnSubscribe<ApiResult>() {
        @Override/*  www .jav  a 2 s.c om*/
        public void call(Subscriber<? super ApiResult> subscriber) {

            if (checkNetwork && !isThereInternetConnection()) {
                subscriber.onError(new NetworkConnectionException(
                        CodeConstants.ApiCode.NETWORK_ERROR + ":" + "Network connection error"));
            } else {
                try {

                    final String api = getApi(doAction) + getGetMethodParams(requestParam);
                    Log.d(TAG, String.format("Request url %s", api));

                    StringRequest request = new StringRequest(Request.Method.GET, api, json -> {
                        Map map = gson.fromJson(json, Map.class);
                        Object code = map.get(CodeConstants.HttpCode.CODE);
                        Object value = map.get(CodeConstants.HttpCode.VALUE);
                        if (CodeConstants.HttpCode.SUCCESS_CODE.equals(code)) {
                            result.setCode(CodeConstants.ApiCode.OK);
                            result.setOriginalCode(String.valueOf(code));
                            result.setValue(gson.toJson(value));
                            subscriber.onNext(result);
                            subscriber.onCompleted();
                        } else {
                            subscriber.onError(new NetworkConnectionException(CodeConstants.ApiCode.ERROR + ":"
                                    + String.valueOf(code) + ":" + value.toString()));
                        }
                        Log.d(TAG, String.format("Request %s success. Result code: %s value: %s", api,
                                CodeConstants.ApiCode.ERROR, value.toString()));
                    }, volleyError -> {
                        subscriber.onError(
                                new NetworkConnectionException(CodeConstants.ApiCode.SERVER_CONNECTION_ERROR
                                        + ":" + (volleyError != null ? volleyError.getMessage() : "")));
                        Log.d(TAG,
                                String.format("Request %s failure. Result code: %s message: %s", api,
                                        CodeConstants.ApiCode.SERVER_CONNECTION_ERROR,
                                        volleyError != null ? volleyError.getMessage() : ""));
                    }) {
                        @Override
                        protected Response<String> parseNetworkResponse(NetworkResponse response) {
                            String setCookie = response.headers.get("Set-Cookie");
                            if (StringUtils.isNotEmpty(setCookie)) {
                                mCookie = setCookie;
                            }
                            Log.d(TAG, "Response cookie " + mCookie);
                            String json = "";
                            if (shouldCache) {
                                int maxAge = 7 * 24 * 60 * 60;
                                response.headers.remove("Cache-Control");
                                response.headers.remove("Pragma");
                                response.headers.remove("Expires");
                                if (refreshCache) {
                                    invalidateCached(api);
                                }
                                try {
                                    json = new String(response.data,
                                            HttpHeaderParser.parseCharset(response.headers));
                                } catch (UnsupportedEncodingException e) {
                                    Log.e(TAG, e.getMessage(), e);
                                }
                                return Response.success(json, cache(response, maxAge));
                            }

                            return super.parseNetworkResponse(response);
                        }

                        @Override
                        public Map<String, String> getHeaders() throws AuthFailureError {
                            Map<String, String> localHashMap = new HashMap<String, String>();
                            if (StringUtils.isNotEmpty(mCookie)) {
                                localHashMap.put("Cookie", mCookie);
                            }
                            return localHashMap;
                        }
                    };
                    request.setShouldCache(shouldCache);
                    requestQueue.add(request);

                } catch (Exception e) {
                    subscriber.onError(new NetworkConnectionException(e.getCause()));
                }
            }

        }
    });
}

From source file:org.soapwsj.SoapClient.java

private HttpPost generatePost(String soapAction, String requestEnvelope) {
    try {//from   w w w.  j a  v  a 2  s.co m
        HttpPost post = new HttpPost(endpointUri.toString());
        // avoid using ISO character set.
        StringEntity contentEntity = new StringEntity(requestEnvelope, "UTF-8");
        post.setEntity(contentEntity);
        if (requestEnvelope.contains(SOAP_1_1_NAMESPACE)) {
            soapAction = soapAction != null ? "\"" + soapAction + "\"" : "";
            post.addHeader(PROP_SOAP_ACTION_11, soapAction);
            post.addHeader(PROP_CONTENT_TYPE, MIMETYPE_TEXT_XML);
            client.getParams().setParameter(PROP_CONTENT_TYPE, MIMETYPE_TEXT_XML);
        } else if (requestEnvelope.contains(SOAP_1_2_NAMESPACE)) {
            String contentType = MIMETYPE_APPLICATION_XML;
            if (soapAction != null) {
                contentType = contentType + PROP_DELIMITER + PROP_SOAP_ACTION_12 + "\"" + soapAction + "\"";
            }
            post.addHeader(PROP_CONTENT_TYPE, contentType);
        }
        return post;
    } catch (UnsupportedEncodingException ex) {
        throw new SoapException(ex.getMessage(), ex);
    }
}

From source file:com.heliumv.api.cc.ClevercureApi.java

@Override
@POST//w  w w  .  ja v a2  s  .  c  o m
@Consumes("text/xml")
public void receiveAnyCCData(@QueryParam(Param.COMPANYCODE) String companyCode,
        @QueryParam(Param.TOKEN) String token,
        //         @QueryParam("user") String user,
        //         @QueryParam("password") String password, 
        @QueryParam(Param.DATATYPE) @DefaultValue("osd") String datatype, String ccdata) {
    if (StringHelper.isEmpty(Param.COMPANYCODE)) {
        respondBadRequestValueMissing(Param.COMPANYCODE);
    }

    try {
        if ("osd".equals(datatype)) {
            //            try {
            //               String oldString = "\u00DF";
            //               String newString = new String(oldString.getBytes("UTF-8"), "UTF-8");
            //               System.out.println(newString.equals(oldString));
            //            } catch(UnsupportedEncodingException e) {
            //               System.out.println("use " +  e.getMessage()) ;
            //            }
            //
            String encoded = null;
            try {
                encoded = new String(ccdata.getBytes("UTF-8"), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                System.out.println("uee " + e.getMessage());
            }

            //            receiveCCDataOsd(companyCode, token, ccdata);
            receiveCCDataOsd(companyCode, token, encoded);
            return;
        }

        respondNotFound();
    } catch (RemoteException e) {
        respondUnavailable(e);
    } catch (NamingException e) {
        respondUnavailable(e);
    }
}

From source file:org.openhab.habdroid.ui.OpenHABWidgetArrayAdapter.java

public void sendItemCommand(OpenHABItem item, String command) {
    try {/* w w w  .  j av  a 2s .c  om*/
        Log.d(HABApplication.getLogTag(),
                String.format("[AsyncHttpClient] POST Request for OpenHABItem = '%s'   command = '%s'",
                        item.getLink(), command));
        StringEntity se = new StringEntity(command);
        mAsyncHttpClient.post(getContext(), item.getLink(), se, "text/plain", new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                Log.d(HABApplication.getLogTag(), "Command was sent successfully");
            }

            @Override
            public void onFailure(Throwable error, String errorResponse) {
                Log.e(HABApplication.getLogTag(), "Got command error " + error.getMessage());
                if (errorResponse != null)
                    Log.e(HABApplication.getLogTag(), "Error response = " + errorResponse);
            }
        });
    } catch (UnsupportedEncodingException e) {
        if (e != null)
            Log.e(HABApplication.getLogTag(), e.getMessage());
    }
}

From source file:net.fluxo.dd.FluxoWSProcess.java

/**
 * Add a bittorrent URL to current list of downloads for the server to process.
 * <p>URL to reach this method: http://[address-or-ip]:[port]/comm/rs/ws/addtorrent/[user-id]/[torrent-url]</p>
 *
 * @param htRequest  a HttpServletRequest object
 * @param uri   bittorrent magnet url or http torrent url to download
 * @param owner user ID associated with this download
 * @return a string containing the status of the request; "OK" followed by download ID or an error message
 *///w w  w . j a  v a2  s  .c om
@GET
@Path("/addtorrent/{owner}/{uri}")
@Produces("text/plain")
public Response getTorrentUrl(@Context HttpServletRequest htRequest,
        @DefaultValue("") @PathParam("uri") String uri, @DefaultValue("") @PathParam("owner") String owner) {
    String username = htRequest.getHeader("DDUSER");
    String password = htRequest.getHeader("DDPWD");
    if (username == null || password == null || !DbControl.authCredentials(username, password)) {
        return Response.status(400).entity("NOT-AUTHORIZED").build();
    }
    try {
        if (uri.length() > 0 && owner.length() > 0) {
            String decodedURL = URLDecoder.decode(uri, "UTF-8");
            String response = OAria.processRequest(decodedURL, owner, false, "", "");
            return Response.status(200).entity(response).build();
        }
    } catch (UnsupportedEncodingException uee) {
        return Response.status(500).entity(uee.getMessage()).build();
    }
    return Response.status(400).entity("EITHER-URI-ERROR-OR-NO-OWNER").build();
}

From source file:net.fluxo.dd.FluxoWSProcess.java

/**
 * Add a video site URL to current list of downloads for the server to process.
 * @param htRequest a HttpServletRequest object
 * @param uri video URL from a supported video sharing website
 * @param owner user ID associated with this download
 * @return a string containing the status of the request; "OK" followed by download ID or an error message
 *///  ww w  . j a va  2 s  .  c  o m
@GET
@Path("/addvid/{owner}/{uri}")
@Produces("text/plain")
public Response addNewVideoDownload(@Context HttpServletRequest htRequest,
        @DefaultValue("") @PathParam("uri") String uri, @DefaultValue("") @PathParam("owner") String owner) {
    String username = htRequest.getHeader("DDUSER");
    String password = htRequest.getHeader("DDPWD");
    if (username == null || password == null || !DbControl.authCredentials(username, password)) {
        return Response.status(400).entity("NOT-AUTHORIZED").build();
    }
    try {
        if (uri.length() > 0 && owner.length() > 0) {
            String decodedURL = URLDecoder.decode(uri, "UTF-8");
            String response = OVideoP.processRequest(decodedURL, owner);
            return Response.status(200).entity(response).build();
        }
    } catch (UnsupportedEncodingException uee) {
        return Response.status(500).entity(uee.getMessage()).build();
    }
    return Response.status(400).entity("EITHER-URI-ERROR-OR-NO-OWNER").build();
}