Example usage for com.google.common.base Functions toStringFunction

List of usage examples for com.google.common.base Functions toStringFunction

Introduction

In this page you can find the example usage for com.google.common.base Functions toStringFunction.

Prototype

public static Function<Object, String> toStringFunction() 

Source Link

Document

Returns a function that calls toString() on its argument.

Usage

From source file:org.apache.solr.core.ConfigSolrXml.java

private void storeConfigPropertyAsString(String section, NamedList<Object> config, CfgProp propertyKey,
        String name) {//from   www  . j ava 2  s  . c om
    storeConfigProperty(section, config, propertyKey, name, Functions.toStringFunction(), String.class);
}

From source file:org.kuali.rice.kew.dto.DTOConverter.java

private static Element createDocumentContentSection(Document document, Element existingAttributeElement,
        List<WorkflowAttributeDefinition> definitions, String content, String elementName,
        String documentTypeName) throws SAXException, IOException, ParserConfigurationException {
    Element contentSectionElement = existingAttributeElement;
    // if they've updated the content, we're going to re-build the content section element from scratch
    if (content != null) {
        if (!org.apache.commons.lang.StringUtils.isEmpty(content)) {
            contentSectionElement = document.createElement(elementName);
            // if they didn't merely clear the content, let's build the content section element by combining the children
            // of the incoming XML content
            Element incomingAttributeElement = XmlHelper.readXml(content).getDocumentElement();
            NodeList children = incomingAttributeElement.getChildNodes();
            for (int index = 0; index < children.getLength(); index++) {
                contentSectionElement.appendChild(document.importNode(children.item(index), true));
            }/*from ww w  .  j  av a2 s.  co m*/
        } else {
            contentSectionElement = null;
        }
    }
    // if they have new definitions we're going to append those to the existing content section
    if (definitions != null && !definitions.isEmpty()) {
        String errorMessage = "";
        boolean inError = false;
        if (contentSectionElement == null) {
            contentSectionElement = document.createElement(elementName);
        }
        for (WorkflowAttributeDefinition definitionVO : definitions) {
            AttributeDefinition definition = convertWorkflowAttributeDefinition(definitionVO);
            ExtensionDefinition extensionDefinition = definition.getExtensionDefinition();

            Object attribute = null;
            attribute = GlobalResourceLoader.getObject(definition.getObjectDefinition());
            if (attribute == null) {
                attribute = GlobalResourceLoader
                        .getService(QName.valueOf(definition.getExtensionDefinition().getResourceDescriptor()));
            }

            if (attribute instanceof XmlConfiguredAttribute) {
                ((XmlConfiguredAttribute) attribute)
                        .setExtensionDefinition(definition.getExtensionDefinition());
            }
            boolean propertiesAsMap = false;
            if (KewApiConstants.RULE_XML_ATTRIBUTE_TYPE.equals(extensionDefinition.getType())) {
                propertiesAsMap = true;
            }
            if (propertiesAsMap) {
                for (org.kuali.rice.kew.api.document.PropertyDefinition propertyDefinitionVO : definitionVO
                        .getPropertyDefinitions()) {
                    if (attribute instanceof GenericXMLRuleAttribute) {
                        ((GenericXMLRuleAttribute) attribute).getParamMap().put(propertyDefinitionVO.getName(),
                                propertyDefinitionVO.getValue());
                    }
                }
            }

            // validate inputs from client application if the attribute is capable
            if (attribute instanceof WorkflowAttributeXmlValidator) {
                List<? extends RemotableAttributeErrorContract> errors = ((WorkflowAttributeXmlValidator) attribute)
                        .validateClientRoutingData();
                if (!errors.isEmpty()) {
                    inError = true;
                    errorMessage += "Error validating attribute " + definitionVO.getAttributeName() + " ";
                    errorMessage += Joiner.on("; ")
                            .join(Iterables.transform(errors, Functions.toStringFunction()));
                }
            }
            // dont add to xml if attribute is in error
            if (!inError) {
                if (attribute instanceof WorkflowRuleAttribute) {
                    String attributeDocContent = ((WorkflowRuleAttribute) attribute).getDocContent();
                    if (!StringUtils.isEmpty(attributeDocContent)) {
                        XmlHelper.appendXml(contentSectionElement, attributeDocContent);
                    }
                } else if (attribute instanceof SearchableAttribute) {
                    SearchableAttribute searchableAttribute = (SearchableAttribute) attribute;
                    String searchableAttributeContent = searchableAttribute
                            .generateSearchContent(extensionDefinition, documentTypeName, definitionVO);
                    if (!StringUtils.isBlank(searchableAttributeContent)) {
                        XmlHelper.appendXml(contentSectionElement, searchableAttributeContent);
                    }
                }
            }
        }
        if (inError) {
            throw new WorkflowRuntimeException(errorMessage);
        }

    }
    if (contentSectionElement != null) {
        // always be sure and import the element into the new document, if it originated from the existing doc content
        // and
        // appended to it, it will need to be imported
        contentSectionElement = (Element) document.importNode(contentSectionElement, true);
    }
    return contentSectionElement;
}

From source file:org.apache.kudu.client.ConnectToCluster.java

/**
 * Checks if we've already received a response or an exception from every master that
 * we've sent a ConnectToMaster to. If so -- and no leader has been found
 * (that is, 'responseD' was never called) -- pass a {@link NoLeaderFoundException}
 * to responseD./*from   w  ww  .ja v a 2s.c  o m*/
 */
private void incrementCountAndCheckExhausted() {
    if (countResponsesReceived.incrementAndGet() == numMasters) {
        if (responseDCalled.compareAndSet(false, true)) {

            // We want `allUnrecoverable` to only be true if all the masters came back with
            // NonRecoverableException so that we know for sure we can't retry anymore. Just one master
            // that replies with RecoverableException or with an ok response but is a FOLLOWER is
            // enough to keep us retrying.
            boolean allUnrecoverable = true;
            if (exceptionsReceived.size() == countResponsesReceived.get()) {
                for (Exception ex : exceptionsReceived) {
                    if (!(ex instanceof NonRecoverableException)) {
                        allUnrecoverable = false;
                        break;
                    }
                }
            } else {
                allUnrecoverable = false;
            }

            String allHosts = NetUtil.hostsAndPortsToString(masterAddrs);
            if (allUnrecoverable) {
                // This will stop retries.
                String msg = String.format("Couldn't find a valid master in (%s). " + "Exceptions received: %s",
                        allHosts,
                        Joiner.on(",").join(Lists.transform(exceptionsReceived, Functions.toStringFunction())));
                Status s = Status.ServiceUnavailable(msg);
                responseD.callback(new NonRecoverableException(s));
            } else {
                String message = String.format("Master config (%s) has no leader.", allHosts);
                Exception ex;
                if (exceptionsReceived.isEmpty()) {
                    LOG.warn(String.format("None of the provided masters (%s) is a leader, will retry.",
                            allHosts));
                    ex = new NoLeaderFoundException(Status.ServiceUnavailable(message));
                } else {
                    LOG.warn(String.format("Unable to find the leader master (%s), will retry", allHosts));
                    String joinedMsg = message + " Exceptions received: " + Joiner.on(",")
                            .join(Lists.transform(exceptionsReceived, Functions.toStringFunction()));
                    Status s = Status.ServiceUnavailable(joinedMsg);
                    ex = new NoLeaderFoundException(s, exceptionsReceived.get(exceptionsReceived.size() - 1));
                }
                responseD.callback(ex);
            }
        }
    }
}

From source file:com.blackducksoftware.bdio.io.LinkedDataContext.java

/**
 * Expand a node such that all known identifiers are fully expanded.
 *///from  ww w .j  a  va  2s  .  c  o m
public Map<String, Object> expand(Node node) {
    // Maps.newLinkedHashMapWithExpectedSize(int) wasn't introduced until Guava 19.0
    Map<String, Object> result = new LinkedHashMap<>(((2 + node.data().size()) * 2) / 3);
    if (node.id() != null) {
        // Expand the identifier against the base IRI
        result.put(JsonLdKeyword.ID.toString(), expandIri(node.id(), true));
    }
    if (!node.types().isEmpty()) {
        // Type instances are already fully qualified IRI, no need to expand
        result.put(JsonLdKeyword.TYPE.toString(),
                FluentIterable.from(node.types()).transform(Functions.toStringFunction()).toList());
    }
    for (Entry<Term, Object> entry : node.data().entrySet()) {
        // Expand the value, term instances are already fully qualified
        TermDefinition definition = termDefinitions.getUnchecked(entry.getKey());
        Object value = expandValue(definition, entry.getValue());
        if (value != null) {
            result.put(entry.getKey().toString(), value);
        }
    }
    return result;
}

From source file:org.jclouds.joyent.cloudapi.v6_5.domain.Machine.java

/**
 * /*from w  w w  .j  a v  a 2s.  co m*/
 * <h4>note</h4>
 * 
 * If the value is a string, it will be quoted, as that's how json strings are represented.
 * 
 * @return key to a json literal of the value
 * @see Metadata#valueType
 * @see Json#fromJson
 */
public Map<String, String> getMetadataAsJsonLiterals() {
    return Maps.transformValues(metadata, Functions.toStringFunction());
}

From source file:com.comphenix.undyingsun.CommandUndying.java

/**
 * Retrieve the string value of all the entries in the iterable.
 * @param iterable - the iterable to convert.
 * @return The string value of each entry.
 *///www  . j ava  2  s  .  c  om
private Iterable<String> asStrings(Iterable<? extends Object> iterable) {
    return Iterables.transform(iterable, Functions.toStringFunction());
}

From source file:com.eucalyptus.ws.server.ServiceAccessLoggingHandler.java

@Override
public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
    try {/*from   w w  w  .  j a va  2s .c o m*/
        if (e instanceof MessageEvent) {
            final MessageEvent msge = (MessageEvent) e;
            if (msge.getMessage() instanceof MappingHttpResponse) {// Handle single request-response MEP
                MappingHttpResponse httpMessage = (MappingHttpResponse) ((MessageEvent) e).getMessage();
                createLogEntry(ctx, httpMessage.getMessage(),
                        Objects.toString(httpMessage.getStatus(), "UNKNOWN"));
            }
        } else if (e instanceof ExceptionEvent) {
            Throwable reply = ((ExceptionEvent) e).getCause();
            String[] extra = new String[] {};
            try {
                final List<Throwable> causalChain = Throwables.getCausalChain(reply);
                extra = (String[]) Collections2.transform(causalChain, Functions.toStringFunction()).toArray();
            } catch (Exception e1) {
                Logger.getLogger("LoggingError." + ServiceAccessLoggingHandler.class.getCanonicalName())
                        .debug(e1);
            }
            createLogEntry(ctx, reply, extra);
        }
    } catch (Exception e1) {
        Logger.getLogger("LoggingError." + ServiceAccessLoggingHandler.class.getCanonicalName()).debug(e1);
    }
    ctx.sendDownstream(e);
}

From source file:edu.harvard.med.screensaver.ui.screens.ScreenSearchResults.java

private List<TableColumn<Screen, ?>> buildScreenResultColumns() {
    List<TableColumn<Screen, ?>> columns = Lists.newArrayList();

    // TODO: should make this a vocab list, but need support for list-of-vocab column type
    columns.add(new EnumEntityColumn<Screen, ScreenResultAvailability>(Screen.screenResult, "Screen Result",
            "'available' if the screen result is loaded into Screensaver and viewable by the current user;"
                    + " 'not shared' if loaded but not viewable by the current user; otherwise 'none'",
            TableColumn.UNGROUPED, ScreenResultAvailability.values()) {
        @Override//from ww  w  .  j  a va2s  . co  m
        public ScreenResultAvailability getCellValue(Screen screen) {
            if (screen.getScreenResult() == null) {
                return ScreenResultAvailability.NONE;
            } else if (screen.getScreenResult().isRestricted()) {
                return ScreenResultAvailability.NOT_SHARED;
            } else {
                return ScreenResultAvailability.AVAILABLE;
            }
        }

        @Override
        protected Comparator<Screen> getAscendingComparator() {
            return new Comparator<Screen>() {
                private NullSafeComparator<ScreenResult> _srComparator = new NullSafeComparator<ScreenResult>(
                        true) {
                    @Override
                    protected int doCompare(ScreenResult sr1, ScreenResult sr2) {
                        if (!sr1.isRestricted() && sr2.isRestricted()) {
                            return -1;
                        }
                        if (sr1.isRestricted() && !sr2.isRestricted()) {
                            return 1;
                        }
                        return sr1.getScreen().getFacilityId().compareTo(sr2.getScreen().getFacilityId());
                    }
                };

                public int compare(Screen s1, Screen s2) {
                    return _srComparator.compare(s1.getScreenResult(), s2.getScreenResult());
                }
            };
        }
    });

    columns.add(new TextSetEntityColumn<Screen>(Screen.screenResult.to(ScreenResult.dataColumns),
            "Assay Readout Type", "The assay readout type for the screen", TableColumn.UNGROUPED) {
        @Override
        public Set<String> getCellValue(Screen screen) {
            if (screen.getScreenResult() != null) { // conditional check, fixes issue #107 - adding the "Assay Readout Type" column causes an exception
                return Sets.newHashSet(Iterables.transform(screen.getScreenResult().getAssayReadoutTypes(),
                        Functions.toStringFunction()));
            } else {
                return Sets.newHashSet();
            }
        }
    });
    columns.get(columns.size() - 1).setAdministrative(true);
    columns.get(columns.size() - 1).setVisible(false);

    return columns;
}

From source file:org.jclouds.joyent.cloudapi.v6_5.domain.Machine.java

/**
 * Any "extra" metadata this machine has
 * /*from   w w w .ja  va2  s  . co m*/
 * <h4>note</h4>
 * 
 * metadata can contain arbitrarily complex values. If the value has structure, you should use
 * {@link #getMetadataAsJsonLiterals}
 * 
 */
public Map<String, String> getMetadata() {
    return Maps.transformValues(metadata, Functions.compose(Functions.toStringFunction(), unquoteString));
}

From source file:org.obiba.magma.beans.BeanVariableValueSourceFactory.java

protected Variable doBuildVariable(Class<?> propertyType, String name) {
    ValueType type = ValueType.Factory.forClass(propertyType);

    Variable.Builder builder = Variable.Builder.newVariable(name, type, entityType);
    if (propertyType.isEnum()) {
        Enum<?>[] constants = (Enum<?>[]) propertyType.getEnumConstants();
        String[] names = Iterables.toArray(
                Iterables.transform(Arrays.asList(constants), Functions.toStringFunction()), String.class);
        builder.addCategories(names);//from  w ww. j a va 2  s . co  m
    }

    if (occurrenceGroup != null) {
        builder.repeatable().occurrenceGroup(occurrenceGroup);
    }

    builder.accept(variableBuilderVisitors);

    // Allow extended classes to contribute to the builder
    return buildVariable(builder).build();
}