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:com.krawler.br.spring.RConverterImpl.java

public Map convertWithFile(HttpServletRequest request, Map reqParams) throws ProcessException {
    HashMap itemMap = new HashMap(), tmpMap = new HashMap();
    try {//  w  w w . j  a  v a 2  s.  c o m
        FileItemFactory factory = new DiskFileItemFactory(4096, new File("/tmp"));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(1000000);
        List fileItems = upload.parseRequest(request);
        Iterator iter = fileItems.iterator();

        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            String key = item.getFieldName();
            OperationParameter o = (OperationParameter) reqParams.get(key);
            if (reqParams.containsKey(key)) {
                if (item.isFormField()) {
                    putItem(tmpMap, key,
                            getValue(item.getString("UTF-8"), mb.getModuleDefinition(o.getType())));
                } else {
                    File destDir = new File(StorageHandler.GetProfileImgStorePath());
                    if (!destDir.exists()) {
                        destDir.mkdirs();
                    }

                    File f = new File(destDir, UUID.randomUUID() + "_" + item.getName());
                    try {
                        item.write(f);
                    } catch (Exception ex) {
                        Logger.getLogger(RConverterImpl.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    putItem(tmpMap, key, f.getAbsolutePath());
                }
            }
        }

        iter = tmpMap.keySet().iterator();

        while (iter.hasNext()) {
            String key = (String) iter.next();
            OperationParameter o = (OperationParameter) reqParams.get(key);
            itemMap.put(key, convertToMultiType((List) tmpMap.get(key), o.getMulti(), o.getType()));
        }

    } catch (FileUploadException ex) {
        throw new ProcessException(ex.getMessage(), ex);
    } catch (UnsupportedEncodingException e) {
        throw new ProcessException(e.getMessage(), e);
    }
    return itemMap;
}

From source file:com.github.maoo.indexer.webscripts.NodeChangesWebScript.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {

    final String serviceContextPath = req.getServerPath() + req.getServiceContextPath();

    //start time//from w w w.j  a v a  2s .  c om
    long startTime = System.currentTimeMillis();

    //Fetching request params
    Map<String, String> templateArgs = req.getServiceMatch().getTemplateVars();
    String storeId = templateArgs.get("storeId");
    String storeProtocol = templateArgs.get("storeProtocol");
    String lastTxnIdString = req.getParameter("lastTxnId");
    String lastAclChangesetIdString = req.getParameter("lastAclChangesetId");
    String maxTxnsString = req.getParameter("maxTxns");
    String maxAclChangesetsString = req.getParameter("maxAclChangesets");

    //Parsing parameters passed from the WebScript invocation
    Long lastTxnId = (lastTxnIdString == null ? null : Long.valueOf(lastTxnIdString));
    Long lastAclChangesetId = (lastAclChangesetIdString == null ? null
            : Long.valueOf(lastAclChangesetIdString));
    Integer maxTxns = (maxTxnsString == null ? maxNodesPerTxns : Integer.valueOf(maxTxnsString));
    Integer maxAclChangesets = (maxAclChangesetsString == null ? maxNodesPerAcl
            : Integer.valueOf(maxAclChangesetsString));

    JSONObject indexingFilters = null;
    try {
        indexingFilters = req.getParameter("indexingFilters") != null
                ? (JSONObject) JSONValue.parse(URLDecoder.decode(req.getParameter("indexingFilters"), "UTF-8"))
                : null;
    } catch (UnsupportedEncodingException e) {
        throw new WebScriptException(e.getMessage(), e);
    }

    logger.debug(String.format("Invoking Changes Webscript, using the following params\n" + "lastTxnId: %s\n"
            + "lastAclChangesetId: %s\n" + "storeId: %s\n" + "storeProtocol: %s\n" + "indexingFilters: %s\n",
            lastTxnId, lastAclChangesetId, storeId, storeProtocol, indexingFilters));

    //Indexing filters
    Filters filters = null;
    if (indexingFilters != null)
        filters = this.getIndexingFilters(indexingFilters);

    //Getting the Store ID on which the changes are requested
    Pair<Long, StoreRef> store = nodeDao.getStore(new StoreRef(storeProtocol, storeId));
    if (store == null) {
        throw new IllegalArgumentException("Invalid store reference: " + storeProtocol + "://" + storeId);
    }

    Set<NodeEntity> nodes = new HashSet<NodeEntity>();
    //Updating the last IDs being processed
    //Depending on params passed to the request, results will be rendered out
    if (lastTxnId == null) {
        lastTxnId = new Long(0);
    }
    List<NodeEntity> nodesFromTxns = indexingService.getNodesByTransactionId(store, lastTxnId, maxTxns,
            filters);
    if (nodesFromTxns != null && nodesFromTxns.size() > 0) {
        nodes.addAll(nodesFromTxns);
    }

    //Set the last database transaction ID or increment it by maxTxns
    Long lastTxnIdDB = indexingService.getLastTransactionID();

    if ((lastTxnId + maxTxns) > lastTxnIdDB) {
        lastTxnId = lastTxnIdDB;
    } else {
        lastTxnId += maxTxns;
    }

    if (lastAclChangesetId == null) {
        lastAclChangesetId = new Long(0);
    }
    List<NodeEntity> nodesFromAcls = indexingService.getNodesByAclChangesetId(store, lastAclChangesetId,
            maxAclChangesets, filters);
    if (nodesFromAcls != null && nodesFromAcls.size() > 0) {
        nodes.addAll(nodesFromAcls);
    }

    //Set the last database aclChangeSet ID or increment it by maxAclChangesets
    Long lastAclChangesetIdDB = indexingService.getLastAclChangeSetID();

    if ((lastAclChangesetId + maxAclChangesets) > lastAclChangesetIdDB) {
        lastAclChangesetId = lastAclChangesetIdDB;
    } else {
        lastAclChangesetId += maxAclChangesets;
    }

    //elapsed time
    long elapsedTime = System.currentTimeMillis() - startTime;

    //Render them out
    Map<String, Object> model = new HashMap<String, Object>(1, 1.0f);
    model.put("qnameDao", qnameDao);
    model.put("nsResolver", namespaceService);
    model.put("nodes", nodes);
    model.put("lastTxnId", lastTxnId);
    model.put("lastAclChangesetId", lastAclChangesetId);
    model.put("storeId", storeId);
    model.put("storeProtocol", storeProtocol);
    model.put("serviceContextPath", serviceContextPath);
    model.put("propertiesUrlPrefix", propertiesUrlPrefix);
    model.put("elapsedTime", elapsedTime);

    //This allows to call the static method QName.createQName from the FTL template
    try {
        BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
        TemplateHashModel staticModels = wrapper.getStaticModels();
        TemplateHashModel qnameStatics = (TemplateHashModel) staticModels
                .get("org.alfresco.service.namespace.QName");
        model.put("QName", qnameStatics);
    } catch (Exception e) {
        throw new AlfrescoRuntimeException(
                "Cannot add BeansWrapper for static QName.createQName method to be used from a Freemarker template",
                e);
    }

    logger.debug(String.format("Attaching %s nodes to the WebScript template", nodes.size()));

    return model;
}

From source file:com.jiangge.apns4j.impl.ApnsConnectionImpl.java

@Override
public void sendNotification(PushNotification notification) {
    byte[] plBytes = null;
    String payload = notification.getPayload().toString();
    try {//from w  w w  .  j av  a 2  s.  com
        plBytes = payload.getBytes(CHARSET_ENCODING);
        if (plBytes.length > PAY_LOAD_MAX_LENGTH) {
            logger.error("Payload execeed limit, the maximum size allowed is 256 bytes. " + payload);
            return;
        }
    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage(), e);
        return;
    }

    /**
     * EN: If error happened before, just wait until the resending work finishes by another thread
     *     and close the current socket
     * CN: ??error-response?????????  
     */
    synchronized (lock) {
        if (errorHappendedLastConn) {
            closeSocket(socket);
            socket = null;
        }
        byte[] data = notification.generateData(plBytes);
        boolean isSuccessful = false;
        int retries = 0;
        while (retries < maxRetries) {
            try {
                boolean exceedIntervalTime = lastSuccessfulTime > 0
                        && (System.currentTimeMillis() - lastSuccessfulTime) > intervalTime;
                if (exceedIntervalTime) {
                    closeSocket(socket);
                    socket = null;
                }

                if (socket == null || socket.isClosed()) {
                    socket = createNewSocket();
                }

                OutputStream socketOs = socket.getOutputStream();
                socketOs.write(data);
                socketOs.flush();
                isSuccessful = true;
                break;
            } catch (Exception e) {
                logger.error(connName + " " + e.getMessage(), e);
                closeSocket(socket);
                socket = null;
            }
            retries++;
        }
        if (!isSuccessful) {
            logger.error(String.format("%s Notification send failed. %s", connName, notification));
            return;
        } else {
            logger.info(String.format("%s Send success. count: %s, notificaion: %s", connName,
                    notificaionSentCount.incrementAndGet(), notification));

            notificationCachedQueue.add(notification);
            lastSuccessfulTime = System.currentTimeMillis();

            /** TODO there is a bug, maybe, theoretically.
             *  CN: ?????? maxCacheLength ?APNS?
             *      ??error-response??
             *      ??100?????APNS??
             */
            if (notificationCachedQueue.size() > maxCacheLength) {
                notificationCachedQueue.poll();
            }
        }
    }

    if (isFirstWrite) {
        isFirstWrite = false;
        /**
         * EN: When we create a socket, just a TCP/IP connection created. After we wrote data to the stream,
         *     the SSL connection had been created. Now, it's time to read data from InputStream
         * CN: createSocket?TCPSSL???????
         *     ?InputStream
         */
        startErrorWorker();
    }
}

From source file:fi.hoski.web.forms.RaceEntryServlet.java

private JSONObject fromCookie(HttpServletRequest request) throws JSONException {
    if (useCookies) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (COOKIENAME.equals(cookie.getName())) {
                    Base64 decoder = new Base64();
                    try {
                        return new JSONObject(new String(decoder.decode(cookie.getValue()), "UTF-8"));
                    } catch (UnsupportedEncodingException ex) {
                        log(ex.getMessage(), ex);
                        return new JSONObject();
                    }/*  w ww  .jav a2  s.co  m*/
                }
            }
        }
    }
    return new JSONObject();

}

From source file:com.eschava.forevernote.FullPageService.java

private String[] processContent(InputStream stream, String encoding, String url) throws IOException {
    HtmlCleaner cleaner = new HtmlCleaner();
    TagNode node = cleaner.clean(stream, encoding);

    HTMLToEvernoteVisitor visitor = new HTMLToEvernoteVisitor(new URL(url));
    visitor.visitDocument(node);//from w  w w  .  j a  v a  2s . c o m

    String title = visitor.getTitle().replaceAll("\\p{Cc}", ""); // p{Cc} is "Other, Control" group. Taken from Constants.EDAM_NOTE_TITLE_REGEX
    // trim title if it is too long
    if (title.length() > TITLE_LEN_MAX)
        title = title.substring(0, TITLE_LEN_MAX) + "...";

    String body = visitor.toString();
    String charset = visitor.getCharset();

    if (encoding.equals(DEFAULT_CHARSET) && charset != null && !charset.equals(encoding)) {
        try {
            title = convert(title, encoding, charset);
            body = convert(body, encoding, charset);
        } catch (UnsupportedEncodingException e) {
            log.log(Level.WARNING, e.getMessage(), e);
        }
    }

    return new String[] { title, body };
}

From source file:hadoop.inputsplit.FastaLineRecordReader.java

public FastaLineRecordReader() {
    try {//from   w ww  .  j a  va  2  s  .  c  om
        this.recordDelimiterBytes = "\n".getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        LOG.error(e.getMessage());
    }
}

From source file:com.xtructure.xutil.AbstractRunTests.java

/**
 * Processes the given file resource.//from w  w  w  . ja  v a  2 s  . c om
 * 
 * @param packageName
 *            the name of the package currently being processed
 * 
 * @param resourceUrl
 *            the URL of the file resource to process
 */
private final void processFileResource(final String packageName, final URL resourceUrl) {
    try {
        final File dir = new File(URLDecoder.decode(resourceUrl.getPath(), "UTF-8"));
        if (!dir.exists()) {
            throw new RuntimeException("directory for resource '" + resourceUrl + "' doesn't exist");
        }
        for (final File file : dir.listFiles()) {
            if (file.isDirectory()) {
                processResources(String.format( //
                        "%s.%s", packageName, file.getName()));
            } else if (isTestClassFileName(file.getName())) {
                addClass(packageName + "." + stripSuffix(file.getName()));
            }
        }
    } catch (UnsupportedEncodingException unsupportedEncodingEx) {
        throw new RuntimeException(
                "couldn't decode resource '" + resourceUrl + "': " + unsupportedEncodingEx.getMessage(),
                unsupportedEncodingEx);
    }
}

From source file:com.mobiperf_library.Checkin.java

private String serviceRequest(String url, String jsonString) throws IOException {

    if (this.accountSelector == null) {
        accountSelector = new AccountSelector(context);
    }/* ww  w  .  j  ava2  s .c o  m*/
    if (!accountSelector.isAnonymous()) {
        synchronized (this) {
            if (authCookie == null) {
                if (!checkGetCookie()) {
                    throw new IOException("No authCookie yet");
                }
            }
        }
    }

    HttpClient client = getNewHttpClient();
    String fullurl = (accountSelector.isAnonymous() ? phoneUtils.getAnonymousServerUrl()
            : phoneUtils.getServerUrl()) + "/" + url;
    Logger.i("Checking in to " + fullurl);
    HttpPost postMethod = new HttpPost(fullurl);

    StringEntity se;
    try {
        se = new StringEntity(jsonString);
    } catch (UnsupportedEncodingException e) {
        throw new IOException(e.getMessage());
    }
    postMethod.setEntity(se);
    postMethod.setHeader("Accept", "application/json");
    postMethod.setHeader("Content-type", "application/json");
    if (!accountSelector.isAnonymous()) {
        // TODO(mdw): This should not be needed
        postMethod.setHeader("Cookie", authCookie.getName() + "=" + authCookie.getValue());
    }

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    Logger.i("Sending request: " + fullurl);
    String result = client.execute(postMethod, responseHandler);
    return result;
}

From source file:com.surevine.alfresco.connector.SimpleAlfrescoHttpConnector.java

/**
 * Adds the get paramters to a string url
 *//*from  www.j  a  v a  2 s  .  c om*/
private String addUrlParameters(final String url, final Map<String, String> parameters) {
    if (parameters == null) {
        return url;
    }

    boolean questionMark = !url.contains("?");

    final StringBuilder output = new StringBuilder(url);

    for (final String key : parameters.keySet()) {
        if (questionMark) {
            output.append("?");
            questionMark = false;
        } else {
            output.append("&");
        }

        try {
            output.append(URLEncoder.encode(key, "UTF-8"));
            output.append("=");
            output.append(parameters.get(key));
        } catch (final UnsupportedEncodingException eUE) {
            LOG.error(eUE.getMessage(), eUE);
        }
    }

    return output.toString();
}