Search in sources :

Example 1 with ActionDoc

use of org.openhab.core.scriptengine.action.ActionDoc in project openhab1-addons by openhab.

the class Prowl method pushNotification.

/**
     * Pushes a Prowl notification
     * 
     * @param apiKey apiKey to use for the notification
     * @param subject the subject of the notification
     * @param message the message of the notification
     * @param priority the priority of the notification (a value between
     *            '-2' and '2')
     * 
     * @return <code>true</code>, if pushing the notification has been successful
     *         and <code>false</code> in all other cases.
     */
@ActionDoc(text = "Pushes a Prowl notification", returns = "<code>true</code>, if successful and <code>false</code> otherwise.")
public static boolean pushNotification(@ParamDoc(name = "apiKey", text = "apiKey to use for the notification.") String apiKey, @ParamDoc(name = "subject", text = "the subject of the notification.") String subject, @ParamDoc(name = "message", text = "the message of the notification.") String message, @ParamDoc(name = "priority", text = "the priority of the notification (a value between '-2' and '2'.") int priority) {
    boolean success = false;
    int normalizedPriority = priority;
    if (priority < -2) {
        normalizedPriority = -2;
        logger.info("Prowl-Notification priority '{}' is invalid - normalized value to '{}'", priority, normalizedPriority);
    } else if (priority > 2) {
        normalizedPriority = 2;
        logger.info("Prowl-Notification priority '{}' is invalid - normalized value to '{}'", priority, normalizedPriority);
    }
    if (ProwlActionService.isProperlyConfigured) {
        ProwlClient client = new ProwlClient();
        if (StringUtils.isNotBlank(Prowl.url)) {
            client.setProwlUrl(Prowl.url);
        }
        ProwlEvent event = new DefaultProwlEvent(apiKey, "openhab", subject, message, normalizedPriority);
        try {
            String returnMessage = client.pushEvent(event);
            logger.info(returnMessage);
            success = true;
        } catch (ProwlException pe) {
            logger.error("pushing prowl event throws exception", pe);
        }
    } else {
        logger.error("Cannot push Prowl notification because of missing configuration settings. The current settings are: " + "apiKey: '{}', priority: {}, url: '{}'", new Object[] { apiKey, String.valueOf(normalizedPriority), url });
    }
    return success;
}
Also used : ProwlClient(net.sourceforge.prowl.api.ProwlClient) DefaultProwlEvent(net.sourceforge.prowl.api.DefaultProwlEvent) ProwlException(net.sourceforge.prowl.exception.ProwlException) ProwlEvent(net.sourceforge.prowl.api.ProwlEvent) DefaultProwlEvent(net.sourceforge.prowl.api.DefaultProwlEvent) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Example 2 with ActionDoc

use of org.openhab.core.scriptengine.action.ActionDoc in project openhab1-addons by openhab.

the class Mail method sendMail.

/**
     * Sends an email with attachment(s) via SMTP
     *
     * @param to the email address of the recipient
     * @param subject the subject of the email
     * @param message the body of the email
     * @param attachmentUrlList a list of URL strings of the contents to send as attachments
     *
     * @return <code>true</code>, if sending the email has been successful and
     *         <code>false</code> in all other cases.
     */
@ActionDoc(text = "Sends an email with attachment via SMTP")
public static boolean sendMail(@ParamDoc(name = "to") String to, @ParamDoc(name = "subject") String subject, @ParamDoc(name = "message") String message, @ParamDoc(name = "attachmentUrlList") List<String> attachmentUrlList) {
    boolean success = false;
    if (MailActionService.isProperlyConfigured) {
        Email email = new SimpleEmail();
        if (attachmentUrlList != null && !attachmentUrlList.isEmpty()) {
            email = new MultiPartEmail();
            for (String attachmentUrl : attachmentUrlList) {
                // Create the attachment
                try {
                    EmailAttachment attachment = new EmailAttachment();
                    attachment.setURL(new URL(attachmentUrl));
                    attachment.setDisposition(EmailAttachment.ATTACHMENT);
                    String fileName = attachmentUrl.replaceFirst(".*/([^/?]+).*", "$1");
                    attachment.setName(isNotBlank(fileName) ? fileName : "Attachment");
                    ((MultiPartEmail) email).attach(attachment);
                } catch (MalformedURLException e) {
                    logger.error("Invalid attachment url.", e);
                } catch (EmailException e) {
                    logger.error("Error adding attachment to email.", e);
                }
            }
        }
        email.setHostName(hostname);
        email.setSmtpPort(port);
        email.setStartTLSEnabled(startTLSEnabled);
        email.setSSLOnConnect(sslOnConnect);
        if (isNotBlank(username)) {
            if (popBeforeSmtp) {
                email.setPopBeforeSmtp(true, hostname, username, password);
            } else {
                email.setAuthenticator(new DefaultAuthenticator(username, password));
            }
        }
        try {
            if (isNotBlank(charset)) {
                email.setCharset(charset);
            }
            email.setFrom(from);
            String[] toList = to.split(";");
            for (String toAddress : toList) {
                email.addTo(toAddress);
            }
            if (!isEmpty(subject)) {
                email.setSubject(subject);
            }
            if (!isEmpty(message)) {
                email.setMsg(message);
            }
            email.send();
            logger.debug("Sent email to '{}' with subject '{}'.", to, subject);
            success = true;
        } catch (EmailException e) {
            logger.error("Could not send e-mail to '" + to + "'.", e);
        }
    } else {
        logger.error("Cannot send e-mail because of missing configuration settings. The current settings are: " + "Host: '{}', port '{}', from '{}', startTLSEnabled: {}, sslOnConnect: {}, username: '{}', password '{}'", new Object[] { hostname, String.valueOf(port), from, String.valueOf(startTLSEnabled), String.valueOf(sslOnConnect), username, password });
    }
    return success;
}
Also used : MalformedURLException(java.net.MalformedURLException) Email(org.apache.commons.mail.Email) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) SimpleEmail(org.apache.commons.mail.SimpleEmail) MultiPartEmail(org.apache.commons.mail.MultiPartEmail) EmailAttachment(org.apache.commons.mail.EmailAttachment) EmailException(org.apache.commons.mail.EmailException) DefaultAuthenticator(org.apache.commons.mail.DefaultAuthenticator) SimpleEmail(org.apache.commons.mail.SimpleEmail) URL(java.net.URL) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Example 3 with ActionDoc

use of org.openhab.core.scriptengine.action.ActionDoc in project openhab1-addons by openhab.

the class Telegram method sendTelegramPhoto.

@ActionDoc(text = "Sends a Picture, protected by username/password authentication, via Telegram REST API")
public static boolean sendTelegramPhoto(@ParamDoc(name = "group") String group, @ParamDoc(name = "photoURL") String photoURL, @ParamDoc(name = "caption") String caption, @ParamDoc(name = "username") String username, @ParamDoc(name = "password") String password) {
    if (groupTokens.get(group) == null) {
        logger.error("Bot '{}' not defined, action skipped", group);
        return false;
    }
    if (photoURL == null) {
        logger.error("photoURL not defined, action skipped");
        return false;
    }
    // load image from url
    byte[] imageFromURL;
    HttpClient getClient = new HttpClient();
    if (username != null && password != null) {
        getClient.getParams().setAuthenticationPreemptive(true);
        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        getClient.getState().setCredentials(AuthScope.ANY, defaultcreds);
    }
    GetMethod getMethod = new GetMethod(photoURL);
    getMethod.getParams().setSoTimeout(HTTP_PHOTO_TIMEOUT);
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    try {
        int statusCode = getClient.executeMethod(getMethod);
        if (statusCode != HttpStatus.SC_OK) {
            logger.error("Method failed: {}", getMethod.getStatusLine());
            return false;
        }
        imageFromURL = getMethod.getResponseBody();
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: {}", e.toString());
        return false;
    } catch (IOException e) {
        logger.error("Fatal transport error: {}", e.toString());
        return false;
    } finally {
        getMethod.releaseConnection();
    }
    // parse image type
    String imageType;
    try {
        ImageInputStream iis = ImageIO.createImageInputStream(new ByteArrayInputStream(imageFromURL));
        Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(iis);
        if (!imageReaders.hasNext()) {
            logger.error("photoURL does not represent a known image type");
            return false;
        }
        ImageReader reader = imageReaders.next();
        imageType = reader.getFormatName();
    } catch (IOException e) {
        logger.error("cannot parse photoURL as image: {}", e.getMessage());
        return false;
    }
    // post photo to telegram
    String url = String.format(TELEGRAM_PHOTO_URL, groupTokens.get(group).getToken());
    PostMethod postMethod = new PostMethod(url);
    try {
        postMethod.getParams().setContentCharset("UTF-8");
        postMethod.getParams().setSoTimeout(HTTP_PHOTO_TIMEOUT);
        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
        Part[] parts = new Part[caption != null ? 3 : 2];
        parts[0] = new StringPart("chat_id", groupTokens.get(group).getChatId());
        parts[1] = new FilePart("photo", new ByteArrayPartSource(String.format("image.%s", imageType), imageFromURL));
        if (caption != null) {
            parts[2] = new StringPart("caption", caption, "UTF-8");
        }
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
        HttpClient client = new HttpClient();
        int statusCode = client.executeMethod(postMethod);
        if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
            return true;
        }
        if (statusCode != HttpStatus.SC_OK) {
            logger.error("Method failed: {}", postMethod.getStatusLine());
            return false;
        }
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: {}", e.toString());
        return false;
    } catch (IOException e) {
        logger.error("Fatal transport error: {}", e.toString());
        return false;
    } finally {
        postMethod.releaseConnection();
    }
    return true;
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) ImageInputStream(javax.imageio.stream.ImageInputStream) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) IOException(java.io.IOException) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) ByteArrayPartSource(org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource) ByteArrayInputStream(java.io.ByteArrayInputStream) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpException(org.apache.commons.httpclient.HttpException) ImageReader(javax.imageio.ImageReader) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Example 4 with ActionDoc

use of org.openhab.core.scriptengine.action.ActionDoc in project openhab1-addons by openhab.

the class Xpl method sendxPLMessage.

@ActionDoc(text = "Send an xPL Message", returns = "<code>true</code>, if successful and <code>false</code> otherwise.")
public static boolean sendxPLMessage(@ParamDoc(name = "target") String target, @ParamDoc(name = "msgType") String msgType, @ParamDoc(name = "schema") String schema, @ParamDoc(name = "bodyElements") String... bodyElements) {
    xPL_MutableMessageI theMessage = xPL_Utils.createMessage();
    xPL_IdentifierI targetIdentifier = xplTransportService.parseNamedIdentifier(target);
    if (targetIdentifier == null) {
        logger.error("Invalid target identifier");
        return false;
    }
    theMessage.setTarget(targetIdentifier);
    // Parse type
    if (msgType.equalsIgnoreCase("TRIGGER")) {
        theMessage.setType(xPL_MessageI.MessageType.TRIGGER);
    } else if (msgType.equalsIgnoreCase("STATUS")) {
        theMessage.setType(xPL_MessageI.MessageType.STATUS);
    } else if (msgType.equalsIgnoreCase("COMMAND")) {
        theMessage.setType(xPL_MessageI.MessageType.COMMAND);
    } else {
        logger.error("Invalid message type");
        return false;
    }
    // Parse Schema
    int delimPtr = schema.indexOf(".");
    if (delimPtr == -1) {
        logger.error("Invalid/improperly formatted schema class.type");
        return false;
    }
    String schemaClass = schema.substring(0, delimPtr);
    String schemaType = schema.substring(delimPtr + 1);
    if ((schemaClass.length() == 0) || (schemaType.length() == 0)) {
        logger.error("Empty/missing parts of schema class.type");
        return false;
    }
    theMessage.setSchema(schemaClass, schemaType);
    // Parse name/value pairs
    String theName = null;
    String theValue = null;
    theMessage.clearMessageBody();
    for (int pairPtr = 0; pairPtr < bodyElements.length; pairPtr++) {
        if ((delimPtr = bodyElements[pairPtr].indexOf("=")) == -1) {
            logger.error("Invalid message body name/value pair");
            return false;
        }
        if ((theName = bodyElements[pairPtr].substring(0, delimPtr)).length() == 0) {
            logger.error("Empty name in message body name/value pair");
            return false;
        }
        theValue = bodyElements[pairPtr].substring(delimPtr + 1);
        theMessage.addNamedValue(theName, theValue);
    }
    xplTransportService.sendMessage(theMessage);
    return true;
}
Also used : org.cdp1802.xpl.xPL_IdentifierI(org.cdp1802.xpl.xPL_IdentifierI) org.cdp1802.xpl.xPL_MutableMessageI(org.cdp1802.xpl.xPL_MutableMessageI) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Example 5 with ActionDoc

use of org.openhab.core.scriptengine.action.ActionDoc in project openhab1-addons by openhab.

the class XMPP method sendXMPP.

// provide public static methods here
/**
     * Sends a message to an XMPP user.
     * 
     * @param to the XMPP address to send the message to
     * @param message the message to send
     * 
     * @return <code>true</code>, if sending the message has been successful and
     *         <code>false</code> in all other cases.
     */
@ActionDoc(text = "Sends a message to an XMPP user.")
public static boolean sendXMPP(@ParamDoc(name = "to") String to, @ParamDoc(name = "message") String message) {
    boolean success = false;
    try {
        XMPPConnection conn = XMPPConnect.getConnection();
        ChatManager chatmanager = ChatManager.getInstanceFor(conn);
        Chat newChat = chatmanager.createChat(to, null);
        try {
            while (message.length() >= 2000) {
                newChat.sendMessage(message.substring(0, 2000));
                message = message.substring(2000);
            }
            newChat.sendMessage(message);
            logger.debug("Sent message '{}' to '{}'.", message, to);
            success = true;
        } catch (XMPPException e) {
            logger.warn("Error Delivering block", e);
        } catch (NotConnectedException e) {
            logger.warn("Error Delivering block", e);
        }
    } catch (NotInitializedException e) {
        logger.warn("Could not send XMPP message as connection is not correctly initialized!");
    }
    return success;
}
Also used : NotConnectedException(org.jivesoftware.smack.SmackException.NotConnectedException) MultiUserChat(org.jivesoftware.smackx.muc.MultiUserChat) Chat(org.jivesoftware.smack.Chat) XMPPConnection(org.jivesoftware.smack.XMPPConnection) XMPPException(org.jivesoftware.smack.XMPPException) ChatManager(org.jivesoftware.smack.ChatManager) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Aggregations

ActionDoc (org.openhab.core.scriptengine.action.ActionDoc)14 Message (com.ciscospark.Message)2 SparkException (com.ciscospark.SparkException)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 IOException (java.io.IOException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 ImageInputStream (javax.imageio.stream.ImageInputStream)2 AddressException (javax.mail.internet.AddressException)2 DefaultHttpMethodRetryHandler (org.apache.commons.httpclient.DefaultHttpMethodRetryHandler)2 HttpClient (org.apache.commons.httpclient.HttpClient)2 HttpException (org.apache.commons.httpclient.HttpException)2 PostMethod (org.apache.commons.httpclient.methods.PostMethod)2 NotConnectedException (org.jivesoftware.smack.SmackException.NotConnectedException)2 XMPPException (org.jivesoftware.smack.XMPPException)2 MultiUserChat (org.jivesoftware.smackx.muc.MultiUserChat)2 TwitterException (twitter4j.TwitterException)2 InputStream (java.io.InputStream)1 BigDecimal (java.math.BigDecimal)1 MalformedURLException (java.net.MalformedURLException)1 URL (java.net.URL)1