List of usage examples for java.lang Throwable getLocalizedMessage
public String getLocalizedMessage()
From source file:org.openhab.binding.smartmeter.internal.SmartMeterHandler.java
/** * Get new data the device//from ww w . j ava 2 s . c o m * */ private void updateOBISValue() { cancelRead(); valueChangeListener = new MeterValueListener() { @Override public <Q extends @NonNull Quantity<Q>> void valueChanged(MeterValue<Q> value) { ThingBuilder thingBuilder = editThing(); String obis = value.getObisCode(); String obisChannelString = SmartMeterBindingConstants.getObisChannelId(obis); Channel channel = thing.getChannel(obisChannelString); ChannelTypeUID channelTypeId = channelTypeProvider.getChannelTypeIdForObis(obis); ChannelType channelType = channelTypeProvider.getChannelType(channelTypeId, null); if (channelType != null) { String itemType = channelType.getItemType(); State state = getStateForObisValue(value, channel); if (channel == null) { logger.debug("Adding channel: {} with item type: {}", obisChannelString, itemType); // channel has not been created yet ChannelBuilder channelBuilder = ChannelBuilder .create(new ChannelUID(thing.getUID(), obisChannelString), itemType) .withType(channelTypeId); Configuration configuration = new Configuration(); configuration.put(SmartMeterBindingConstants.CONFIGURATION_CONVERSION, 1); channelBuilder.withConfiguration(configuration); channelBuilder.withLabel(obis); Map<String, String> channelProps = new HashMap<>(); channelProps.put(SmartMeterBindingConstants.CHANNEL_PROPERTY_OBIS, obis); channelBuilder.withProperties(channelProps); channelBuilder.withDescription(MessageFormat .format("Value for OBIS code: {0} with Unit: {1}", obis, value.getUnit())); channel = channelBuilder.build(); ChannelUID channelId = channel.getUID(); // add all valid channels to the thing builder List<Channel> channels = new ArrayList<Channel>(getThing().getChannels()); if (channels.stream().filter((element) -> element.getUID().equals(channelId)) .count() == 0) { channels.add(channel); thingBuilder.withChannels(channels); updateThing(thingBuilder.build()); } } if (!channel.getProperties().containsKey(SmartMeterBindingConstants.CHANNEL_PROPERTY_OBIS)) { addObisPropertyToChannel(obis, channel); } updateState(channel.getUID(), state); updateStatus(ThingStatus.ONLINE, ThingStatusDetail.NONE); } else { logger.warn("No ChannelType found for OBIS {}", obis); } } private void addObisPropertyToChannel(String obis, Channel channel) { String description = channel.getDescription(); String label = channel.getLabel(); ChannelBuilder newChannel = ChannelBuilder.create(channel.getUID(), channel.getAcceptedItemType()) .withDefaultTags(channel.getDefaultTags()).withConfiguration(channel.getConfiguration()) .withDescription(description == null ? "" : description).withKind(channel.getKind()) .withLabel(label == null ? "" : label).withType(channel.getChannelTypeUID()); HashMap<String, String> properties = new HashMap<>(channel.getProperties()); properties.put(SmartMeterBindingConstants.CHANNEL_PROPERTY_OBIS, obis); newChannel.withProperties(properties); updateThing(editThing().withoutChannel(channel.getUID()).withChannel(newChannel.build()).build()); } @Override public <Q extends @NonNull Quantity<Q>> void valueRemoved(MeterValue<Q> value) { // channels that are not available are removed String obisChannelId = SmartMeterBindingConstants.getObisChannelId(value.getObisCode()); logger.debug("Removing channel: {}", obisChannelId); ThingBuilder thingBuilder = editThing(); thingBuilder.withoutChannel(new ChannelUID(thing.getUID(), obisChannelId)); updateThing(thingBuilder.build()); } @Override public void errorOccurred(Throwable e) { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getLocalizedMessage()); } }; this.smlDevice.addValueChangeListener(valueChangeListener); SmartMeterConfiguration config = getConfigAs(SmartMeterConfiguration.class); int delay = config.refresh != null ? config.refresh : DEFAULT_REFRESH_PERIOD; valueReader = this.smlDevice.readValues(DEFAULT_TIMEOUT, this.scheduler, Duration.ofSeconds(delay)); }
From source file:com.github.richardwilly98.esdms.services.AuthenticationProvider.java
@Override public boolean exists(String id) throws ServiceException { try {// www .j ava 2 s . c om if (log.isTraceEnabled()) { log.trace(String.format("exists - %s", id)); } return client.prepareGet(index, type, id).setFields(new String[0]).execute().actionGet().isExists(); } catch (Throwable t) { log.error("exists failed", t); throw new ServiceException(t.getLocalizedMessage()); } }
From source file:dk.netarkivet.common.webinterface.HTMLUtils.java
/** * Forward to our standard error message page with an internationalized message, in case of exception. Note that * this <em>doesn't</em> throw ForwardedToErrorPage, it is the job of whoever calls this to do that if not within a * JSP page (a JSP page can just return immediately). All text involved will be HTML-escaped. * * @param context The context that the error happened in (the JSP-defined pageContext, typically) * @param i18n The i18n information/*from w ww .j a v a 2s .co m*/ * @param e The exception that is being handled. * @param label An i18n label for the error. This label should begin with "errormsg;". * @param args Any extra args for i18n * @throws IOFailure If the forward fails */ public static void forwardWithErrorMessage(PageContext context, I18n i18n, Throwable e, String label, Object... args) { // Note that we may not want to be to strict here // as otherwise information could be lost. ArgumentNotValid.checkNotNull(context, "context"); ArgumentNotValid.checkNotNull(I18N, "I18N"); ArgumentNotValid.checkNotNull(label, "label"); ArgumentNotValid.checkNotNull(args, "args"); String msg = HTMLUtils.escapeHtmlValues(i18n.getString(context.getResponse().getLocale(), label, args)); context.getRequest().setAttribute("message", msg + "\n" + e.getLocalizedMessage()); RequestDispatcher rd = context.getServletContext().getRequestDispatcher("/message.jsp"); final String errormsg = "Failed to forward on error " + msg; try { rd.forward(context.getRequest(), context.getResponse()); } catch (IOException e1) { log.warn(errormsg, e1); throw new IOFailure(errormsg, e1); } catch (ServletException e1) { log.warn(errormsg, e1); throw new IOFailure(errormsg, e1); } }
From source file:org.opencms.workplace.administration.A_CmsImportFromHttp.java
/** * Creates the HTML for the error message if validation errors were found.<p> * //from ww w.ja v a 2 s . co m * @return the HTML for the error message if validation errors were found */ protected String createDialogErrorMessage() { if (getException() != null) { StringBuffer result = new StringBuffer(8); result.append(dialogBlockStart("")); result.append("<table border=\"0\">\n"); result.append("<tr><td><img src=\""); result.append(getSkinUri()).append("commons/"); result.append("error.png"); result.append("\" border=\"0\" alt=\"\"></td><td class=\"xmlTdError maxwidth\">"); Throwable t = getException(); while (t != null) { result.append(t.getLocalizedMessage()); t = t.getCause(); if (t != null) { result.append("<br>"); } } result.append("</table>\n"); result.append(dialogBlockEnd()); return result.toString(); } return ""; }
From source file:com.github.richardwilly98.esdms.services.AuthenticationProvider.java
@Override public void delete(SessionImpl session) throws ServiceException { try {//from w ww . j a v a2 s . c om if (log.isTraceEnabled()) { log.trace(String.format("delete - %s", session)); } if (session == null) { throw new IllegalArgumentException("session is null"); } client.prepareDelete(index, type, session.getId()).execute().actionGet(); } catch (Throwable t) { log.error("delete failed", t); throw new ServiceException(t.getLocalizedMessage()); } }
From source file:com.github.richardwilly98.esdms.services.AuthenticationProvider.java
@Override public SessionImpl update(SessionImpl session) throws ServiceException { try {//from w ww . j a v a2 s . c om String json = mapper.writeValueAsString(session); client.prepareDelete(index, type, session.getId()); UpdateResponse response = client.prepareUpdate(index, type, session.getId()).setDoc(json) .setRetryOnConflict(5).execute().actionGet(); // refreshIndex(); SessionImpl updatedSession = get(response.getId()); return updatedSession; } catch (Throwable t) { log.error("update failed", t); throw new ServiceException(t.getLocalizedMessage()); } }
From source file:com.github.richardwilly98.esdms.services.AuthenticationProvider.java
@Override public SessionImpl get(String id) throws ServiceException { try {// w w w.j a v a 2s . c o m // if (log.isTraceEnabled()) { // log.trace(String.format("get - %s", id)); // } GetResponse response = client.prepareGet(index, type, id).execute().actionGet(); if (!response.isExists()) { log.info(String.format("Cannot find item %s", id)); return null; } String json = response.getSourceAsString(); SessionImpl session = mapper.readValue(json, SessionImpl.class); // validateSession(session); return session; } catch (Throwable t) { log.error("get failed", t); throw new ServiceException(t.getLocalizedMessage()); } }
From source file:org.geotools.gce.imagemosaic.Utils.java
/** * Creates a mosaic for the provided input parameters. * /*from ww w . j a va2s .c o m*/ * @param location * path to the directory where to gather the elements for the * mosaic. * @param indexName * name to give to this mosaic * @param wildcard * wildcard to use for walking through files. We are using * commonsIO for this task * @param absolutePath * tells the catalogue builder to use absolute paths. * @param hints hints to control reader instantiations * @return <code>true</code> if everything is right, <code>false</code>if * something bad happens, in which case the reason should be logged * to the logger. */ static boolean createMosaic(final String location, final String indexName, final String wildcard, final boolean absolutePath, final Hints hints) { // create a mosaic index builder and set the relevant elements final CatalogBuilderConfiguration configuration = new CatalogBuilderConfiguration(); configuration.setAbsolute(absolutePath); configuration.setHints(hints); configuration.setRootMosaicDirectory(location); configuration.setIndexingDirectories(Arrays.asList(location)); configuration.setIndexName(indexName); // create the builder final CatalogBuilder catalogBuilder = new CatalogBuilder(configuration); // this is going to help us with catching exceptions and logging them final Queue<Throwable> exceptions = new LinkedList<Throwable>(); try { final CatalogBuilder.ProcessingEventListener listener = new CatalogBuilder.ProcessingEventListener() { @Override public void exceptionOccurred(ExceptionEvent event) { final Throwable t = event.getException(); exceptions.add(t); if (LOGGER.isLoggable(Level.SEVERE)) LOGGER.log(Level.SEVERE, t.getLocalizedMessage(), t); } @Override public void getNotification(ProcessingEvent event) { if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine(event.getMessage()); } }; catalogBuilder.addProcessingEventListener(listener); catalogBuilder.run(); } catch (Throwable e) { LOGGER.log(Level.SEVERE, "Unable to build mosaic", e); return false; } finally { catalogBuilder.dispose(); } // check that nothing bad happened if (exceptions.size() > 0) return false; return true; }
From source file:org.ajax4jsf.templatecompiler.elements.vcp.FCallTemplateElement.java
public FCallTemplateElement(final Node element, final CompilationContext componentBean) throws CompilationException { super(element, componentBean); this.useOnlyEnumeratingParaments = false; NamedNodeMap nnm = element.getAttributes(); Node functionNameNode = nnm.getNamedItem(FUNCTION_NAME_ATTRIBUTE_NAME); if (functionNameNode != null) { this.functionName = functionNameNode.getNodeValue(); } else {// w ww . j a v a2 s .co m throw new CompilationException("function name is not set"); } Node nodeUseOnlyThisParameters = nnm.getNamedItem(USE_ONLY_THIS_PARAMETERS); if (nodeUseOnlyThisParameters != null) { this.useOnlyEnumeratingParaments = Boolean.getBoolean(nodeUseOnlyThisParameters.getNodeValue()); } // if // read name of variable if need Node variableName = nnm.getNamedItem(VAR_ATTRIBUTE_NAME); if (variableName != null) { this.variable = variableName.getNodeValue(); } // if // read name of parameters if need ParameterProcessor parameterProcessor = new ParameterProcessor(element, componentBean); this.parameters = parameterProcessor.getParameters(); log.debug(this.parameters); List decodeFunctionName = null; decodeFunctionName = Arrays.asList(this.functionName.split(FUNCTION_DELIMITER)); if (null == decodeFunctionName) { decodeFunctionName = new ArrayList(); decodeFunctionName.add(this.functionName); } ArrayList functionNames = new ArrayList(); String lastClassName = componentBean.getFullBaseclass(); for (Iterator iter = decodeFunctionName.iterator(); iter.hasNext();) { String elementFunction = (String) iter.next(); try { log.debug("Try to load class : " + lastClassName); Class clazz = componentBean.loadClass(lastClassName); if (!iter.hasNext()) { String method = getMethod(clazz, elementFunction); if (method != null) { log.debug(method); functionNames.add(method); } else { log.error("Method " + elementFunction + " not found in class : " + lastClassName); throw new CompilationException(); } } else { // // Probing properties !!!! // PropertyDescriptor propertyDescriptor = getPropertyDescriptor(clazz, elementFunction); if (propertyDescriptor != null) { functionNames.add(propertyDescriptor.getReadMethod().getName() + "()"); log.debug("Property " + elementFunction + " mapped to function : " + propertyDescriptor.getReadMethod().getName()); lastClassName = propertyDescriptor.getPropertyType().getName(); } else { log.error("Property " + elementFunction + " not found in class : " + lastClassName); throw new CompilationException(); } } } catch (Throwable e) { log.error("Error load class : " + lastClassName + ", " + e.getLocalizedMessage()); e.printStackTrace(); throw new CompilationException("Error load class : " + lastClassName, e); } } StringBuffer tmpbuf = new StringBuffer(); for (Iterator iter = functionNames.iterator(); iter.hasNext();) { String tmpElement = (String) iter.next(); if (tmpbuf.length() != 0) { tmpbuf.append("."); } tmpbuf.append(tmpElement); } this.fullFunctionName = tmpbuf.toString(); }
From source file:com.github.richardwilly98.esdms.services.AuthenticationProvider.java
@Override public SessionImpl create(SessionImpl item) throws ServiceException { try {/* w ww . j ava 2 s . c om*/ if (log.isTraceEnabled()) { log.trace(String.format("create - %s", item)); } if (item.getId() == null) { item.setId(generateUniqueId()); } String json; json = mapper.writeValueAsString(item); IndexResponse response = client.prepareIndex(index, type).setId(item.getId()).setSource(json).execute() .actionGet(); log.trace(String.format("Index: %s - Type: %s - Id: %s", response.getIndex(), response.getType(), response.getId())); refreshIndex(); SessionImpl newSession = get(response.getId()); return newSession; } catch (Throwable t) { log.error("create failed", t); throw new ServiceException(t.getLocalizedMessage()); } }