Example usage for java.io UnsupportedEncodingException getLocalizedMessage

List of usage examples for java.io UnsupportedEncodingException getLocalizedMessage

Introduction

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

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:org.eclipse.kura.web.server.servlet.FileServlet.java

private void doGetIcon(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String queryString = req.getQueryString();

    if (queryString == null) {
        s_logger.error("Error parsing query string.");
        throw new ServletException("Error parsing query string.");
    }//  ww w.  j a  v a  2s  .  com

    // Parse the query string
    Map<String, String> pairs;
    try {
        pairs = parseQueryString(queryString);
    } catch (UnsupportedEncodingException e) {
        s_logger.error("Error parsing query string.");
        throw new ServletException("Error parsing query string: " + e.getLocalizedMessage());
    }

    // Check for malformed request
    if (pairs == null || pairs.size() != 1) {
        s_logger.error("Error parsing query string.");
        throw new ServletException("Error parsing query string.");
    }

    String pid = pairs.get("pid");
    if (pid != null && pid.length() > 0) {
        BundleContext ctx = Console.getBundleContext();
        Bundle[] bundles = ctx.getBundles();
        ServiceLocator locator = ServiceLocator.getInstance();

        // Iterate over bundles to find PID
        for (Bundle b : bundles) {
            MetaTypeService mts;
            try {
                mts = locator.getService(MetaTypeService.class);
            } catch (GwtKuraException e1) {
                s_logger.error("Error parsing query string.");
                throw new ServletException("Error parsing query string.");
            }
            MetaTypeInformation mti = mts.getMetaTypeInformation(b);

            String[] pids = mti.getPids();
            for (String p : pids) {
                if (p.equals(pid)) {
                    try {
                        InputStream is = mti.getObjectClassDefinition(pid, null).getIcon(32);
                        if (is == null) {
                            s_logger.error("Error reading icon file.");
                            throw new ServletException("Error reading icon file.");
                        }
                        OutputStream os = resp.getOutputStream();
                        byte[] buffer = new byte[1024];
                        for (int length = 0; (length = is.read(buffer)) > 0;) {
                            os.write(buffer, 0, length);
                        }
                        is.close();
                        os.close();

                    } catch (IOException e) {
                        s_logger.error("Error reading icon file.");
                        throw new IOException("Error reading icon file.");
                    }
                }
            }
        }
    } else {
        s_logger.error("Error parsing query string.");
        throw new ServletException("Error parsing query string.");
    }

}

From source file:com.amalto.service.calltransformer.CallTransformerServiceBean.java

public String receiveFromInbound(ItemPOJOPK itemPK, String routingOrderID, String parameters)
        throws com.amalto.core.util.XtentisException {
    try {/*  w w  w . jav a2  s .  com*/
        String transformer = null;
        if (parameters != null) {
            String kvs[] = parameters.split("&");
            for (String kv1 : kvs) {
                String[] kv = kv1.split("=");
                String key = kv[0].trim().toLowerCase();
                if ((Param_Transformer_Name.equals(key)) && (kv.length == 2)) {
                    transformer = kv[1].trim();
                }
            }
            if (transformer == null || "".equals(transformer)) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Service CallTransformer - mandatory parameter transformer name is missing");
                }
                throw new XtentisException(
                        "Service CallTransformer - mandatory parameter transformer name is missing");
            }
            Transformer tctrl = Util.getTransformerV2CtrlLocal();
            if (tctrl.existsTransformer(new TransformerV2POJOPK(transformer)) == null) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Service CallTransformer is unable to call transformer " + transformer
                            + " - transformer doesn't exist");
                }
                throw new XtentisException("Unable to find the transformer " + transformer);
            }
            Item ictrl = Util.getItemCtrl2Local();
            ItemPOJO pojo = ictrl.getItem(itemPK);
            TransformerContext context = new TransformerContext(new TransformerV2POJOPK(transformer));
            context.putInPipeline(Transformer.DEFAULT_VARIABLE,
                    new TypedContent(pojo.getProjectionAsString().getBytes(), "text/xml"));
            AbstractRoutingOrderV2POJO routingOrder = getRoutingOrderPOJO();
            String userToken = null;
            if (routingOrder != null) {
                try {
                    userToken = new String(
                            (new BASE64Decoder()).decodeBuffer(routingOrder.getBindingUserToken()), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    LOGGER.error("Unable to read user token.", e);
                }
            }
            TransformerGlobalContext globalContext = new TransformerGlobalContext(context);
            globalContext.setUserToken(userToken);
            tctrl.executeUntilDone(globalContext);
        }
        return "CallTransformer Service successfully executed transformer '" + transformer + "'";
    } catch (Exception e) {
        String err = (new SimpleDateFormat("yyyyMMdd'T'HH:mm:ss, SSS"))
                .format(new Date(System.currentTimeMillis())) + ": ERROR routing to Call Transformer Service "
                + ": " + e.getLocalizedMessage();
        if (e instanceof XtentisException) {
            throw new XtentisException(e);
        } else {
            LOGGER.error(err + " (" + e.getClass().getName() + ")", e);
            throw new XtentisException(e);
        }
    }

}

From source file:com.nononsenseapps.notepad.sync.googleapi.GoogleAPITalker.java

/**
 * Set the pageToken to null to get the first page
 *//*from   w w  w .j ava  2 s  . c o  m*/
private String allTasksUpdatedMin(final String listId, final String timestamp, final String pageToken) {
    // items,nextPageToken
    String request = BASE_TASK_URL + "/" + listId + TASKS
            + "?showDeleted=true&showHidden=true&fields=items%2CnextPageToken&";

    // Comes into play if user has Many tasks
    if (pageToken != null && !pageToken.isEmpty()) {
        request += "pageToken=" + pageToken + "&";
    }

    if (timestamp != null && !timestamp.isEmpty()) {
        try {
            request += "updatedMin=" + URLEncoder.encode(timestamp, "UTF-8") + "&";
        } catch (UnsupportedEncodingException e) {
            // Is OK. Can request full sync.
            Log.d(TAG, "Malformed timestamp: " + e.getLocalizedMessage());
        }
    }

    request += AuthUrlEnd();
    return request;
}

From source file:com.microsoft.tfs.core.clients.versioncontrol.engines.internal.CheckinEngine.java

/**
 * Uploads the file for the given change, unless the MD5 sum of the local
 * file matches the upload hash and we can skip the upload for this file
 * entirely.//w w w  . j a  v a  2s.c  o m
 *
 * @param change
 *        the pending change whose file should be uploaded.
 * @param completionService
 *        where the uploads were submitted (must not be <code>null</code>)
 * @param state
 *        the state kept during checkin to note errors.
 * @throws CheckinException
 *         if the local file was missing.
 * @throws CoreCancelException
 *         if the upload was cancelled by the user.
 */
private void uploadFile(PendingChange change, final CompletionService<WorkerStatus> completionService,
        final AsyncCheckinOperation state) throws CheckinException, CoreCancelException {
    Check.notNull(change, "change"); //$NON-NLS-1$

    /*
     * Callers should only use these methods for pending adds or edits, and
     * we always have a local item for these.
     */
    Check.notNull(change.getLocalItem(), "change.getLocalItem()"); //$NON-NLS-1$

    final String localItem = change.getLocalItem();
    final FileSystemAttributes attrs = FileSystemUtils.getInstance().getAttributes(localItem);
    if (new File(change.getLocalItem()).exists() == false && !attrs.isSymbolicLink()) {
        throw new CheckinException(null, false, false,
                MessageFormat.format(Messages.getString("CheckinEngine.LocalItemNoLongerExistsFormat"), //$NON-NLS-1$
                        change.getLocalItem()));
    }

    /*
     * Handle tpattributes: EOL and AppleSingle encoding. The change
     * variable is set to a cloned change so we can modify the local item
     * for the upload without affecting the caller's use of the original
     * change.
     */
    String filterTempFile = null;
    final GetEngine getEngine = new GetEngine(client);
    final FileAttributesCollection attributes = getEngine.getAttributesForFile(localItem,
            change.getServerItem(), (FileEncoding.BINARY.getCodePage() != change.getEncoding()));

    if (attributes != null) {
        /*
         * Convert end-of-line characters for files that have the extended
         * attribute set.
         */
        final StringPairFileAttribute eolAttribute = attributes
                .getStringPairFileAttribute(FileAttributeNames.SERVER_EOL);

        if (eolAttribute != null && eolAttribute.getValue() != null) {
            final String desiredNewlineSequence = FileAttributeValues
                    .getEndOfLineStringForAttributeValue(eolAttribute);

            if (desiredNewlineSequence == null) {
                throw new CheckinException(null, false, false, MessageFormat.format(
                        Messages.getString("CheckinEngine.UnsupportedServerEOLStyleFormat"), //$NON-NLS-1$
                        eolAttribute.getValue(), change.getLocalItem(), FileAttributesFile.DEFAULT_FILENAME));
            } else if (desiredNewlineSequence.equals("")) //$NON-NLS-1$
            {
                log.debug(MessageFormat.format("Not converting line endings in {0}", change.getLocalItem())); //$NON-NLS-1$
            } else {
                log.debug(MessageFormat.format("Converting line endings for {0} to {1}", //$NON-NLS-1$
                        change.getLocalItem(), eolAttribute.getValue()));

                /*
                 * Create a temporary file for the conversion so we don't
                 * modify the working folder file.
                 */

                try {
                    if (filterTempFile == null) {
                        filterTempFile = createTempFile(change);
                    }

                    Charset charset = CodePageMapping.getCharset(change.getEncoding(), false);

                    if (charset == null) {
                        charset = Charset.defaultCharset();
                    }

                    NewlineUtils.convertFile(new File(filterTempFile), charset, desiredNewlineSequence);

                    log.info(MessageFormat.format("Converted line endings in {0} to {1}", //$NON-NLS-1$
                            filterTempFile, eolAttribute.getValue(), charset.name()));
                } catch (final UnsupportedEncodingException e) {
                    final String message = MessageFormat.format(
                            Messages.getString("CheckinEngine.CouldNotChangeEOLStyleUnknownJavaEncodingFormat"), //$NON-NLS-1$
                            change.getLocalItem(), e.getLocalizedMessage());

                    log.error(message, e);
                    throw new CheckinException(null, false, false, message);
                } catch (final IOException e) {
                    final String message = MessageFormat.format(
                            Messages.getString("CheckinEngine.CouldNotChangeEOLStyleIOExceptionFormat"), //$NON-NLS-1$
                            change.getLocalItem(), e.getLocalizedMessage());

                    log.error(message, e);
                    throw new CheckinException(null, false, false, message);
                }
            }
        }

        /*
         * Encode data fork and resource fork into an AppleSingle file if
         * requested. This should come last (as other filters, above, may
         * modify the data fork and should not modify the AppleSingle file.)
         */
        final StringPairFileAttribute transformAttribute = attributes
                .getStringPairFileAttribute(FileAttributeNames.TRANSFORM);

        if (transformAttribute != null && "apple".equals(transformAttribute.getValue())) //$NON-NLS-1$
        {
            if (Platform.isCurrentPlatform(Platform.MAC_OS_X)) {
                try {
                    if (filterTempFile == null) {
                        filterTempFile = createTempFile(change);
                    }

                    AppleSingleUtil.encodeFile(new File(filterTempFile), change.getLocalItem());
                } catch (final IOException e) {
                    final String message = MessageFormat.format(
                            Messages.getString("CheckinEngine.CouldNotDecodeAppleSingleFileFormat"), //$NON-NLS-1$
                            change.getLocalItem(), e.getLocalizedMessage());

                    log.error(message, e);
                    throw new CheckinException(null, false, false, message);
                }
            } else {
                log.warn(MessageFormat.format("Not preserving Apple metadata for {0} on platform {1}", //$NON-NLS-1$
                        change.getLocalItem(), Platform.getCurrentPlatformString()));
            }
        }
    }

    if (attrs.isSymbolicLink()) {
        /*
         * for symlinks, create temporary file containing the symlink info;
         * upload the temporary file rather than the symlinks
         */
        try {
            final String link = FileSystemUtils.getInstance().getSymbolicLink(localItem);
            filterTempFile = createTempFileForSymbolicLink(localItem, link);
        } catch (final IOException e) {
            final String message = MessageFormat.format(
                    Messages.getString("CheckinEngine.CouldNotCreateTempFileForSymlinkFormat"), //$NON-NLS-1$
                    localItem, e.getLocalizedMessage());

            log.error(message, e);
            throw new CheckinException(null, false, false, message);
        }
    }

    /*
     * We may have done some filtering (EOL conversion or AppleSingle
     * encoding), update the change)
     */
    if (filterTempFile != null) {
        /**
         * Clone the pending change for the upload process, so we can change
         * the local item to the temp item and not affect the working folder
         * updates applied after the upload process finishes (which uses the
         * original change object.
         */
        change = new PendingChange(change);
        change.setLocalItem(filterTempFile);
    }

    // See if we can skip the upload for non-symbolic files.
    final byte[] localMD5Hash = computeMD5Hash(change.getLocalItem(), TaskMonitorService.getTaskMonitor());
    byte[] serverHash = change.getUploadContentHashValue();
    if (serverHash == null) {
        serverHash = change.getHashValue();
    }

    if (serverHash != null && serverHash.length > 0 && Arrays.equals(serverHash, localMD5Hash)) {
        log.trace(
                MessageFormat.format("skipped upload of {0} because hash codes match", change.getLocalItem())); //$NON-NLS-1$

        /*
         * We may have done some sort of upload filtering (EOL conversion or
         * AppleSingle encoding), clean up the file in this case.
         */
        if (filterTempFile != null) {
            TempStorageService.getInstance().cleanUpItem(new File(filterTempFile));
        }

        return;
    }

    /*
     * Let our thread pool execute this task. submit() will block if all the
     * workers are busy (because the completion service wraps a
     * BoundedExecutor), which is what we want. This keeps our upload
     * connections limited so we don't saturate the network with TCP/IP or
     * HTTP overhead or the TFS server with connections.
     *
     * We don't do the MD5 checkin in these threads because keeping that
     * serial is pretty efficient. Parallel MD5 checking may cause us to go
     * disk-bound when we have many small files spread all over the disk
     * (out of cache).
     */
    completionService.submit(new CheckinWorker(TaskMonitorService.getTaskMonitor(), client, workspace, change,
            localMD5Hash, state));
}

From source file:com.yoctopuce.YoctoAPI.YFunction.java

protected int _upload(String pathname, String content) throws YAPI_Exception {
    try {//from  w w  w .j a  v  a2 s. c o  m
        return this._upload(pathname, content.getBytes(YAPI.DefaultEncoding));
    } catch (UnsupportedEncodingException e) {
        throw new YAPI_Exception(YAPI.INVALID_ARGUMENT, e.getLocalizedMessage());
    }
}

From source file:fr.treeptik.cloudunit.service.impl.ApplicationServiceImpl.java

/**
 * Add git container to application associated to server
 *
 * @param application//from w w w .  j  a  v a 2s .c o  m
 * @return
 * @throws ServiceException
 * @throws CheckException
 */
private Module addGitContainer(Application application, String tagName)
        throws ServiceException, CheckException {

    Module moduleGit = ModuleFactory.getModule("git");
    // todo : externaliser la variable
    String containerGitAddress = "/cloudunit/git/.git";

    try {
        // Assign fixed host ports for forwarding git ports (22)
        Map<String, String> mapProxyPorts = portUtils.assignProxyPorts(application);
        String freeProxySshPortNumber = mapProxyPorts.get("freeProxySshPortNumber");

        // Creation of git container fo application
        moduleGit.setName("git");
        moduleGit.setImage(imageService.findByName("git"));
        moduleGit.setApplication(application);

        moduleGit.setSshPort(freeProxySshPortNumber);
        moduleGit = moduleService.initModule(application, moduleGit, tagName);

        application.getModules().add(moduleGit);
        application.setGitContainerIP(moduleGit.getContainerIP());

        application.setGitSshProxyPort(freeProxySshPortNumber);

        // Update GIT respository informations in the current application
        application.setGitAddress("ssh://"
                + AlphaNumericsCharactersCheckUtils.convertToAlphaNumerics(application.getUser().getLogin())
                + "@" + application.getName() + "." + application.getSuffixCloudUnitIO().substring(1) + ":"
                + application.getGitSshProxyPort() + containerGitAddress);

        moduleGit.setStatus(Status.START);
        moduleGit = moduleService.update(moduleGit);

    } catch (UnsupportedEncodingException e) {
        moduleGit.setStatus(Status.FAIL);
        logger.error("Error :  Error during persist git module " + e);
        throw new ServiceException(e.getLocalizedMessage(), e);
    }
    return moduleGit;
}

From source file:com.smartmarmot.dbforbix.config.Config.java

/**
 * Prepare byte array as a request to Zabbix Server
 * @param json string to be sent to Zabbix Server as proxy request
 * @return byte array representation of request ready to be sent
 *///from w w w . j  ava  2 s.  c  o  m
public byte[] getRequestToZabbixServer(String json) {
    String str = new String(ZBX_HEADER_PREFIX + "________" + json);
    //byte[] data=str.getBytes();
    byte[] data;
    try {
        /**
         * For those who want to use russian and other unicode characters
         */
        data = str.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        LOG.error("Problem with encoding json " + e.getLocalizedMessage());
        data = str.getBytes();
    }

    //get size of json request in little-endian format
    byte[] leSize = null;
    leSize = getNumberInLEFormat8B(json.length());
    if (leSize.length != 8) {
        LOG.error("getZabbixProxyRequest():leSize has " + leSize.length + " != 8 bytes!");
        return null;
    }

    for (int i = 0; i < 8; ++i)
        data[i + 5] = leSize[i];
    //LOG.debug("getZabbixProxyRequest(): data: "+ new String(data));
    return data;

}

From source file:com.linkedpipes.plugin.loader.dcatAp11ToDkanBatch.DcatAp11ToDkanBatch.java

private String getToken(String username, String password) throws LpException {
    HttpPost httpPost = new HttpPost(apiURI + "/user/login");

    ArrayList<NameValuePair> postParameters = new ArrayList<>();
    postParameters.add(new BasicNameValuePair("username", username));
    postParameters.add(new BasicNameValuePair("password", password));

    httpPost.addHeader(new BasicHeader("Accept", "application/json"));

    try {//from   ww w  .ja  v a 2 s. c o  m
        httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
    } catch (UnsupportedEncodingException e) {
        LOG.error("Unexpected encoding issue");
    }

    CloseableHttpResponse response = null;
    String token = null;
    try {
        response = postClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == 200) {
            LOG.debug("Logged in");
            token = new JSONObject(EntityUtils.toString(response.getEntity())).getString("token");
        } else {
            String ent = EntityUtils.toString(response.getEntity());
            LOG.error("Response:" + ent);
            throw exceptionFactory.failure("Error logging in: " + ent);
        }
    } catch (Exception e) {
        LOG.error(e.getLocalizedMessage(), e);
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                LOG.error(e.getLocalizedMessage(), e);
                throw exceptionFactory.failure("Error logging in");
            }
        }
    }

    return token;
}

From source file:org.apache.jmeter.samplers.SampleResult.java

/**
 * Sets the responseData attribute of the SampleResult object.
 * Should only be called after setting the dataEncoding (if necessary)
 *
 * @param response/* ww  w .  j  av a 2s  .  c  o m*/
 *            the new responseData value (String)
 *
 * @deprecated - only intended for use from BeanShell code
 */
@Deprecated
public void setResponseData(String response) {
    responseDataAsString = null;
    try {
        responseData = response.getBytes(getDataEncodingWithDefault());
    } catch (UnsupportedEncodingException e) {
        log.warn("Could not convert string, using default encoding. " + e.getLocalizedMessage());
        responseData = response.getBytes(); // N.B. default charset is used deliberately here
    }
}

From source file:com.cloud.storage.resource.VmwareStorageProcessor.java

private static String deriveTemplateUuidOnHost(VmwareHypervisorHost hyperHost, String storeIdentifier,
        String templateName) {/*  ww w.ja  va  2s  . c  o  m*/
    String templateUuid;
    try {
        templateUuid = UUID.nameUUIDFromBytes(
                (templateName + "@" + storeIdentifier + "-" + hyperHost.getMor().getValue()).getBytes("UTF-8"))
                .toString();
    } catch (UnsupportedEncodingException e) {
        s_logger.warn("unexpected encoding error, using default Charset: " + e.getLocalizedMessage());
        templateUuid = UUID
                .nameUUIDFromBytes((templateName + "@" + storeIdentifier + "-" + hyperHost.getMor().getValue())
                        .getBytes(Charset.defaultCharset()))
                .toString();
    }
    templateUuid = templateUuid.replaceAll("-", "");
    return templateUuid;
}