Example usage for org.apache.commons.lang ObjectUtils toString

List of usage examples for org.apache.commons.lang ObjectUtils toString

Introduction

In this page you can find the example usage for org.apache.commons.lang ObjectUtils toString.

Prototype

public static String toString(Object obj) 

Source Link

Document

Gets the toString of an Object returning an empty string ("") if null input.

 ObjectUtils.toString(null)         = "" ObjectUtils.toString("")           = "" ObjectUtils.toString("bat")        = "bat" ObjectUtils.toString(Boolean.TRUE) = "true" 

Usage

From source file:org.openhab.binding.homematic.internal.communicator.parser.CommonRpcParser.java

/**
 * Converts the object to a integer.//ww w .  ja  va 2  s  .  c  o  m
 */
protected Integer toInteger(Object object) {
    if (object == null || object instanceof Integer) {
        return (Integer) object;
    }
    try {
        return Double.valueOf(ObjectUtils.toString(object)).intValue();
    } catch (NumberFormatException ex) {
        return null;
    }
}

From source file:org.openhab.binding.homematic.internal.communicator.parser.CommonRpcParser.java

/**
 * Converts the object to a number./*from   w  ww . j  a va 2s. c o  m*/
 */
protected Number toNumber(Object object) {
    if (object == null || object instanceof Number) {
        return (Number) object;
    }
    return NumberUtils.createNumber(ObjectUtils.toString(object));
}

From source file:org.openhab.binding.homematic.internal.communicator.parser.GetAllScriptsParser.java

/**
 * {@inheritDoc}/*  w w w.  j a v  a  2 s.  c o  m*/
 */
@Override
public Void parse(Object[] message) throws IOException {
    message = (Object[]) message[0];
    for (int i = 0; i < message.length; i++) {
        String scriptName = ObjectUtils.toString(message[i]);
        HmDatapoint dpScript = new HmDatapoint(scriptName, scriptName, HmValueType.BOOL, Boolean.FALSE, false,
                HmParamsetType.VALUES);
        dpScript.setInfo(scriptName);
        channel.addDatapoint(dpScript);
    }
    return null;
}

From source file:org.openhab.binding.homematic.internal.communicator.virtual.DisplayTextVirtualDatapoint.java

/**
 * {@inheritDoc}/*from  w  w  w . j av  a2 s. co m*/
 */
@Override
public void handleCommand(VirtualGateway gateway, HmDatapoint dp, HmDatapointConfig dpConfig, Object value)
        throws IOException, HomematicClientException {
    dp.setValue(value);

    if (DATAPOINT_NAME_DISPLAY_SUBMIT.equals(dp.getName()) && MiscUtils.isTrueValue(dp.getValue())) {
        HmChannel channel = dp.getChannel();
        boolean isEp = isEpDisplay(channel.getDevice());

        List<String> message = new ArrayList<String>();
        message.add(START);
        message.add(LF);

        for (int i = 1; i <= getLineCount(channel.getDevice()); i++) {
            String line = ObjectUtils.toString(
                    channel.getDatapoint(HmParamsetType.VALUES, DATAPOINT_NAME_DISPLAY_LINE + i).getValue());
            if (StringUtils.isEmpty(line)) {
                line = " ";
            }
            message.add(LINE);
            message.add(encodeText(line));
            if (!isEp) {
                String color = channel.getDatapoint(HmParamsetType.VALUES, DATAPOINT_NAME_DISPLAY_COLOR + i)
                        .getOptionValue();
                message.add(COLOR);
                String colorCode = Color.getCode(color);
                message.add(StringUtils.isBlank(colorCode) ? Color.WHITE.getCode() : colorCode);
            }
            String icon = channel.getDatapoint(HmParamsetType.VALUES, DATAPOINT_NAME_DISPLAY_ICON + i)
                    .getOptionValue();
            String iconCode = Icon.getCode(icon);
            if (StringUtils.isNotBlank(iconCode)) {
                message.add(ICON);
                message.add(iconCode);
            }
            message.add(LF);
        }

        if (isEp) {
            String beeper = channel.getDatapoint(HmParamsetType.VALUES, DATAPOINT_NAME_DISPLAY_BEEPER)
                    .getOptionValue();
            message.add(BEEPER_START);
            message.add(Beeper.getCode(beeper));
            message.add(BEEPER_END);
            // set number of beeps
            message.add(encodeBeepCount(
                    channel.getDatapoint(HmParamsetType.VALUES, DATAPOINT_NAME_DISPLAY_BEEPCOUNT)));
            message.add(BEEPCOUNT_END);
            // set interval between two beeps
            message.add(encodeBeepInterval(
                    channel.getDatapoint(HmParamsetType.VALUES, DATAPOINT_NAME_DISPLAY_BEEPINTERVAL)));
            message.add(BEEPINTERVAL_END);
            // LED value must always set (same as beeps)
            String led = channel.getDatapoint(HmParamsetType.VALUES, DATAPOINT_NAME_DISPLAY_LED)
                    .getOptionValue();
            message.add(Led.getCode(led));

        }
        message.add(STOP);

        gateway.sendDatapoint(channel.getDatapoint(HmParamsetType.VALUES, DATAPOINT_NAME_SUBMIT),
                new HmDatapointConfig(), StringUtils.join(message, ","));
    }
}

From source file:org.openhab.binding.homematic.internal.type.HomematicTypeGeneratorImpl.java

private void generateConfigDescription(HmDevice device, URI configDescriptionURI) {
    List<ConfigDescriptionParameter> parms = new ArrayList<ConfigDescriptionParameter>();
    List<ConfigDescriptionParameterGroup> groups = new ArrayList<ConfigDescriptionParameterGroup>();

    for (HmChannel channel : device.getChannels()) {
        String groupName = "HMG_" + channel.getNumber();
        String groupLabel = MetadataUtils.getDescription("CHANNEL_NAME") + " " + channel.getNumber();
        groups.add(new ConfigDescriptionParameterGroup(groupName, null, false, groupLabel, null));

        for (HmDatapoint dp : channel.getDatapoints().values()) {
            if (dp.getParamsetType() == HmParamsetType.MASTER) {
                ConfigDescriptionParameterBuilder builder = ConfigDescriptionParameterBuilder.create(
                        MetadataUtils.getParameterName(dp),
                        MetadataUtils.getConfigDescriptionParameterType(dp));

                builder.withLabel(MetadataUtils.getLabel(dp));
                builder.withDefault(ObjectUtils.toString(dp.getDefaultValue()));
                builder.withDescription(MetadataUtils.getDatapointDescription(dp));

                if (dp.isEnumType()) {
                    builder.withLimitToOptions(dp.isEnumType());
                    List<ParameterOption> options = MetadataUtils.generateOptions(dp,
                            new OptionsBuilder<ParameterOption>() {
                                @Override
                                public ParameterOption createOption(String value, String description) {
                                    return new ParameterOption(value, description);
                                }/*from  w  w w .j  ava2  s.co m*/
                            });
                    builder.withOptions(options);
                }

                if (dp.isNumberType()) {
                    builder.withMinimum(MetadataUtils.createBigDecimal(dp.getMinValue()));
                    builder.withMaximum(MetadataUtils.createBigDecimal(dp.getMaxValue()));
                    builder.withStepSize(
                            MetadataUtils.createBigDecimal(dp.isFloatType() ? new Float(0.1) : 1L));
                    builder.withUnitLabel(MetadataUtils.getUnit(dp));
                }

                builder.withGroupName(groupName);
                parms.add(builder.build());
            }
        }
    }
    if (!parms.isEmpty()) {
        configDescriptionProvider
                .addConfigDescription(new ConfigDescription(configDescriptionURI, parms, groups));
    }

}

From source file:org.openhab.binding.weather.internal.gfx.WeatherTokenResolver.java

/**
 * Replaces the token with a property of the weather object.
 *///w  w w .  ja  v  a  2s. c  om
private String replaceWeather(Token token, Weather instance) throws Exception {
    if (!PropertyUtils.hasProperty(instance, token.name)) {
        throw new RuntimeException("Invalid weather token: " + token.full);
    }
    Object propertyValue = PropertyUtils.getPropertyValue(instance, token.name);
    if (token.unit != null && propertyValue instanceof Double) {
        propertyValue = UnitUtils.convertUnit((Double) propertyValue, token.unit, token.name);
    }
    if (token.formatter != null) {
        return String.format(token.formatter, propertyValue);
    }
    return ObjectUtils.toString(propertyValue);
}

From source file:org.openhab.binding.weather.internal.gfx.WeatherTokenResolver.java

/**
 * Replaces the token with properties of the weather LocationConfig object.
 *//*from   w w w. j  a va2  s  .c  o m*/
private String replaceConfig(Token token) {
    LocationConfig locationConfig = WeatherContext.getInstance().getConfig().getLocationConfig(locationId);
    if (locationConfig == null) {
        throw new RuntimeException("Weather locationId '" + locationId + "' does not exist");
    }

    if ("latitude".equals(token.name)) {
        return locationConfig.getLatitude().toString();
    } else if ("longitude".equals(token.name)) {
        return locationConfig.getLongitude().toString();
    } else if ("name".equals(token.name)) {
        return locationConfig.getName();
    } else if ("language".equals(token.name)) {
        return locationConfig.getLanguage();
    } else if ("updateInterval".equals(token.name)) {
        return ObjectUtils.toString(locationConfig.getUpdateInterval());
    } else if ("locationId".equals(token.name)) {
        return locationConfig.getLocationId();
    } else if ("providerName".equals(token.name)) {
        return ObjectUtils.toString(locationConfig.getProviderName());
    } else {
        throw new RuntimeException("Invalid weather token: " + token.full);
    }
}

From source file:org.pentaho.platform.plugin.action.builtin.EmailComponent.java

@Override
public boolean executeAction() {
    EmailAction emailAction = (EmailAction) getActionDefinition();

    String messagePlain = emailAction.getMessagePlain().getStringValue();
    String messageHtml = emailAction.getMessageHtml().getStringValue();
    String subject = emailAction.getSubject().getStringValue();
    String to = emailAction.getTo().getStringValue();
    String cc = emailAction.getCc().getStringValue();
    String bcc = emailAction.getBcc().getStringValue();
    String from = emailAction.getFrom().getStringValue(defaultFrom);
    if (from.trim().length() == 0) {
        from = defaultFrom;//from   w  w  w  .j  av  a 2 s  .  c om
    }

    /*
     * if( context.getInputNames().contains( "attach" ) ) { //$NON-NLS-1$ Object attachParameter =
     * context.getInputParameter( "attach" ).getValue(); //$NON-NLS-1$ // We have a list of attachments, each element of
     * the list is the name of the parameter containing the attachment // Use the parameter filename portion as the
     * attachment name. if ( attachParameter instanceof String ) { String attachName = context.getInputParameter(
     * "attach-name" ).getStringValue(); //$NON-NLS-1$ AttachStruct attachData = getAttachData( context,
     * (String)attachParameter, attachName ); if ( attachData != null ) { attachments.add( attachData ); } } else if (
     * attachParameter instanceof List ) { for ( int i = 0; i < ((List)attachParameter).size(); ++i ) { AttachStruct
     * attachData = getAttachData( context, ((List)attachParameter).get( i ).toString(), null ); if ( attachData != null
     * ) { attachments.add( attachData ); } } } else if ( attachParameter instanceof Map ) { for ( Iterator it =
     * ((Map)attachParameter).entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry)it.next();
     * AttachStruct attachData = getAttachData( context, (String)entry.getValue(), (String)entry.getKey() ); if (
     * attachData != null ) { attachments.add( attachData ); } } } }
     * 
     * int maxSize = Integer.MAX_VALUE; try { maxSize = new Integer( props.getProperty( "mail.max.attach.size" )
     * ).intValue(); } catch( Throwable t ) { //ignore if not set to a valid value }
     * 
     * if ( totalAttachLength > maxSize ) { // Sort them in order TreeMap tm = new TreeMap(); for( int idx=0;
     * idx<attachments.size(); idx++ ) { // tm.put( new Integer( )) } }
     */

    if (ComponentBase.debug) {
        debug(Messages.getInstance().getString("Email.DEBUG_TO_FROM", to, from)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_CC_BCC", cc, bcc)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_SUBJECT", subject)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_PLAIN_MESSAGE", messagePlain)); //$NON-NLS-1$
        debug(Messages.getInstance().getString("Email.DEBUG_HTML_MESSAGE", messageHtml)); //$NON-NLS-1$
    }

    if ((to == null) || (to.trim().length() == 0)) {

        // Get the output stream that the feedback is going into
        OutputStream feedbackStream = getFeedbackOutputStream();
        if (feedbackStream != null) {
            createFeedbackParameter("to", Messages.getInstance().getString("Email.USER_ENTER_EMAIL_ADDRESS"), //$NON-NLS-1$//$NON-NLS-2$
                    "", "", true); //$NON-NLS-1$ //$NON-NLS-2$
            setFeedbackMimeType("text/html"); //$NON-NLS-1$
            return true;
        } else {
            return false;
        }
    }
    if (subject == null) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0005_NULL_SUBJECT", getActionName())); //$NON-NLS-1$
        return false;
    }
    if ((messagePlain == null) && (messageHtml == null)) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0006_NULL_BODY", getActionName())); //$NON-NLS-1$
        return false;
    }

    if (getRuntimeContext().isPromptPending()) {
        return true;
    }

    try {
        Properties props = new Properties();
        final IEmailService service = PentahoSystem.get(IEmailService.class, "IEmailService",
                PentahoSessionHolder.getSession());
        props.put("mail.smtp.host", service.getEmailConfig().getSmtpHost());
        props.put("mail.smtp.port", ObjectUtils.toString(service.getEmailConfig().getSmtpPort()));
        props.put("mail.transport.protocol", service.getEmailConfig().getSmtpProtocol());
        props.put("mail.smtp.starttls.enable", ObjectUtils.toString(service.getEmailConfig().isUseStartTls()));
        props.put("mail.smtp.auth", ObjectUtils.toString(service.getEmailConfig().isAuthenticate()));
        props.put("mail.smtp.ssl", ObjectUtils.toString(service.getEmailConfig().isUseSsl()));
        props.put("mail.smtp.quitwait", ObjectUtils.toString(service.getEmailConfig().isSmtpQuitWait()));
        props.put("mail.from.default", service.getEmailConfig().getDefaultFrom());
        String fromName = service.getEmailConfig().getFromName();
        if (StringUtils.isEmpty(fromName)) {
            fromName = Messages.getInstance().getString("schedulerEmailFromName");
        }
        props.put("mail.from.name", fromName);
        props.put("mail.debug", ObjectUtils.toString(service.getEmailConfig().isDebug()));

        Session session;
        if (service.getEmailConfig().isAuthenticate()) {
            props.put("mail.userid", service.getEmailConfig().getUserId());
            props.put("mail.password", service.getEmailConfig().getPassword());
            Authenticator authenticator = new EmailAuthenticator();
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // debugging is on if either component (xaction) or email config debug is on
        if (service.getEmailConfig().isDebug() || ComponentBase.debug) {
            session.setDebug(true);
        }

        // construct the message
        MimeMessage msg = new MimeMessage(session);
        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        } else {
            // There should be no way to get here
            error(Messages.getInstance().getString("Email.ERROR_0012_FROM_NOT_DEFINED")); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        EmailAttachment[] emailAttachments = emailAction.getAttachments();
        if ((messagePlain != null) && (messageHtml == null) && (emailAttachments.length == 0)) {
            msg.setText(messagePlain, LocaleHelper.getSystemEncoding());
        } else if (emailAttachments.length == 0) {
            if (messagePlain != null) {
                msg.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$          
            }
            if (messageHtml != null) {
                msg.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
            }
        } else {
            // need to create a multi-part message...
            // create the Multipart and add its parts to it
            Multipart multipart = new MimeMultipart();
            // create and fill the first message part
            if (messageHtml != null) {
                // create and fill the first message part
                MimeBodyPart htmlBodyPart = new MimeBodyPart();
                htmlBodyPart.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
                multipart.addBodyPart(htmlBodyPart);
            }

            if (messagePlain != null) {
                MimeBodyPart textBodyPart = new MimeBodyPart();
                textBodyPart.setContent(messagePlain,
                        "text/plain; charset=" + LocaleHelper.getSystemEncoding()); //$NON-NLS-1$
                multipart.addBodyPart(textBodyPart);
            }

            for (EmailAttachment element : emailAttachments) {
                IPentahoStreamSource source = element.getContent();
                if (source == null) {
                    error(Messages.getInstance().getErrorString("Email.ERROR_0015_ATTACHMENT_FAILED")); //$NON-NLS-1$
                    return false;
                }
                DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source);
                String attachmentName = element.getName();
                if (ComponentBase.debug) {
                    debug(Messages.getInstance().getString("Email.DEBUG_ADDING_ATTACHMENT", attachmentName)); //$NON-NLS-1$
                }

                // create the second message part
                MimeBodyPart attachmentBodyPart = new MimeBodyPart();

                // attach the file to the message
                attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
                attachmentBodyPart.setFileName(attachmentName);
                if (ComponentBase.debug) {
                    debug(Messages.getInstance().getString("Email.DEBUG_ATTACHMENT_SOURCE", //$NON-NLS-1$
                            dataSource.getName()));
                }
                multipart.addBodyPart(attachmentBodyPart);
            }

            // add the Multipart to the message
            msg.setContent(multipart);
        }

        msg.setHeader("X-Mailer", EmailComponent.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        if (ComponentBase.debug) {
            debug(Messages.getInstance().getString("Email.DEBUG_EMAIL_SUCCESS")); //$NON-NLS-1$
        }
        return true;
        // TODO: persist the content set for a while...
    } catch (SendFailedException e) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$
        /*
         * Exception ne; MessagingException sfe = e; while ((ne = sfe.getNextException()) != null && ne instanceof
         * MessagingException) { sfe = (MessagingException) ne;
         * error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", sfe.toString()), sfe);
         * //$NON-NLS-1$ }
         */

    } catch (AuthenticationFailedException e) {
        error(Messages.getInstance().getString("Email.ERROR_0014_AUTHENTICATION_FAILED", to), e); //$NON-NLS-1$
    } catch (Throwable e) {
        error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e); //$NON-NLS-1$
    }
    return false;
}

From source file:org.pentaho.platform.plugin.services.email.EmailConfigurationXml.java

public static Document getDocument(final IEmailConfiguration emailConfiguration) {
    final Document document = DocumentHelper.createDocument();
    document.addElement(ROOT_ELEMENT);//from  w w w  . j  a v  a2  s  .c o m
    setValue(document, SMTP_HOST_XPATH, ObjectUtils.toString(emailConfiguration.getSmtpHost()));
    setValue(document, SMTP_PORT_XPATH, ObjectUtils.toString(emailConfiguration.getSmtpPort()));
    setValue(document, SMTP_PROTOCOL_XPATH, ObjectUtils.toString(emailConfiguration.getSmtpProtocol()));
    setValue(document, USE_START_TLS_XPATH,
            ObjectUtils.toString(emailConfiguration.isUseStartTls(), Boolean.FALSE.toString()));
    setValue(document, AUTHENTICATE_XPATH,
            ObjectUtils.toString(emailConfiguration.isAuthenticate(), Boolean.FALSE.toString()));
    setValue(document, USE_SSL_XPATH,
            ObjectUtils.toString(emailConfiguration.isUseSsl(), Boolean.FALSE.toString()));
    setValue(document, DEBUG_XPATH,
            ObjectUtils.toString(emailConfiguration.isDebug(), Boolean.FALSE.toString()));
    setValue(document, SMTP_QUIT_WAIT_XPATH,
            ObjectUtils.toString(emailConfiguration.isSmtpQuitWait(), Boolean.FALSE.toString()));

    setValue(document, DEFAULT_FROM_XPATH, ObjectUtils.toString(emailConfiguration.getDefaultFrom()));
    setValue(document, FROM_NAME_XPATH, ObjectUtils.toString(emailConfiguration.getFromName()));
    setValue(document, USER_ID_XPATH, ObjectUtils.toString(emailConfiguration.getUserId()));
    setValue(document, PASSWORD_XPATH, ObjectUtils.toString(emailConfiguration.getPassword()));
    return document;
}

From source file:org.pentaho.platform.plugin.services.email.EmailService.java

/**
 * Tests the provided email configuration by sending a test email. This will just indicate that the server
 * configuration is correct and a test email was successfully sent. It does not test the destination address.
 * /* w w  w.  j  a  v a2s.co m*/
 * @param emailConfig
 *          the email configuration to test
 * @throws Exception
 *           indicates an error running the test (as in an invalid configuration)
 */
public String sendEmailTest(final IEmailConfiguration emailConfig) {
    final Properties emailProperties = new Properties();
    emailProperties.setProperty("mail.smtp.host", emailConfig.getSmtpHost());
    emailProperties.setProperty("mail.smtp.port", ObjectUtils.toString(emailConfig.getSmtpPort()));
    emailProperties.setProperty("mail.transport.protocol", emailConfig.getSmtpProtocol());
    emailProperties.setProperty("mail.smtp.starttls.enable", ObjectUtils.toString(emailConfig.isUseStartTls()));
    emailProperties.setProperty("mail.smtp.auth", ObjectUtils.toString(emailConfig.isAuthenticate()));
    emailProperties.setProperty("mail.smtp.ssl", ObjectUtils.toString(emailConfig.isUseSsl()));
    emailProperties.setProperty("mail.debug", ObjectUtils.toString(emailConfig.isDebug()));

    Session session = null;
    if (emailConfig.isAuthenticate()) {
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailConfig.getUserId(), emailConfig.getPassword());
            }
        };
        session = Session.getInstance(emailProperties, authenticator);
    } else {
        session = Session.getInstance(emailProperties);
    }

    String sendEmailMessage = "";
    try {
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(emailConfig.getDefaultFrom(), emailConfig.getFromName()));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailConfig.getDefaultFrom()));
        msg.setSubject(messages.getString("EmailService.SUBJECT"));
        msg.setText(messages.getString("EmailService.MESSAGE"));
        msg.setHeader("X-Mailer", "smtpsend");
        msg.setSentDate(new Date());
        Transport.send(msg);
        sendEmailMessage = "EmailTester.SUCESS";
    } catch (Exception e) {
        logger.error(messages.getString("EmailService.NOT_CONFIGURED"), e);
        sendEmailMessage = "EmailTester.FAIL";
    }
    return sendEmailMessage;
}