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.openanzo.client.cli.ConvertCommand.java

int convert(CommandContext context, AnzoClient client, RdfInputArgument input, Writer writer,
        RDFFormat outputFormat, URI defaultNamedGraphUri, URI base, boolean excludeFilePrefixes)
        throws AnzoException {
    int result = 1;

    RDFFormat inputFormat = input.getFormat();
    Reader in = input.getReader();
    Map<String, String> prefixes = Collections.emptyMap();
    Collection<Statement> statements = new HashSet<Statement>();
    if (!inputFormat.supportsNamedGraphs()) {
        if (defaultNamedGraphUri == null) {
            defaultNamedGraphUri = input.getDefaultGraphURI();
        }//from ww w  . j av  a 2  s .  c  om
        if (defaultNamedGraphUri == null && outputFormat.supportsNamespaces()) {
            defaultNamedGraphUri = UriGenerator.generateNamedGraphUri();
        }
        StatementsAndPrefixes sP = ReadWriteUtils.loadStatementsAndPrefixes(in, inputFormat,
                ObjectUtils.toString(base), defaultNamedGraphUri);
        prefixes = sP.getPrefixes();
        statements.addAll(sP.getStatements());
    } else {
        StatementsAndPrefixes stmtsAndPrefixes = ReadWriteUtils.loadStatementsAndPrefixes(in, inputFormat,
                ObjectUtils.toString(base), null);
        statements.addAll(stmtsAndPrefixes.getStatements());
        prefixes = stmtsAndPrefixes.getPrefixes();
    }
    context.outputRdf(statements, outputFormat, writer,
            excludeFilePrefixes ? Collections.<String, String>emptyMap() : prefixes);
    result = 0;

    return result;
}

From source file:org.openanzo.client.cli.GenCommand.java

private int gen(CommandContext context, AnzoClient client, RdfInputArgument input, Writer output, URI base)
        throws AnzoException {
    int result = 1;
    try {/*from w  w  w. ja  va 2  s .c om*/

        IDataset storeIn = new Dataset();

        Reader in = input.getReader();
        RDFFormat inputFormat = input.getFormat();

        if (base == null) {
            base = input.getDefaultGraphURI();
        }

        ReadWriteUtils.loadQuadStore(storeIn, in, inputFormat, ObjectUtils.toString(base));

        for (JastorGeneration gen : SystemFactory.getAllJastorGeneration(storeIn)) {
            JastorContext ctx = new JastorContext();
            if (gen.getGenerateListeners() != null && gen.getGenerateListeners()) {
                ctx.setGenerateListeners(true);
            } else {
                ctx.setGenerateListeners(false);
            }
            for (JastorOntology ont : gen.getJastorOntology()) {
                if (!client.namedGraphExists(ont.getOntologyUri())) {
                    context.writeError("Ontology does not exist: " + ont.getOntologyUri());
                }
                ClientGraph ontGraph = client.getReplicaGraph(ont.getOntologyUri());
                if (ont.getGenerate()) {
                    ctx.addOntologyToGenerate(ontGraph, ont.getOntologyUri().toString(), ont.get_package());
                } else {
                    ctx.addOntologyDependency(ontGraph, ont.getOntologyUri().toString(), ont.get_package());
                }
            }
            JastorGenerator generator = new JastorGenerator(new File(gen.getDestDir()).getCanonicalFile(), ctx);
            generator.run();
        }

        result = 0;
    } catch (IOException e) {
        log.error("Error generating classes", e);
    }
    return result;
}

From source file:org.openanzo.client.cli.QueryCommand.java

int query(CommandContext context, AnzoClient client, String query, RDFFormat outputFormat,
        boolean allDefaultGraphs, boolean allNamedGraphs, boolean allMetadataDefaultGraphs,
        boolean allMetadataNamedGraphs, RdfInputArgument datasetInput, boolean queryTime, URI base,
        boolean prettyPrint, boolean rewriteAndPrint, boolean skipCache, URI datasource) throws AnzoException {

    QueryResults queryResults = null;/* w  w w .  j  a v a  2 s .  com*/

    String fullQuery = null;
    StringBuilder builder = new StringBuilder();

    int hiddenPrefixCount = 0;
    if (!context.getExcludePrefixes()) {
        hiddenPrefixCount = context.getPrefixes().size();
        for (Map.Entry<String, String> prefix : context.getPrefixes().entrySet()) {
            builder.append("PREFIX ");
            builder.append(prefix.getKey());
            builder.append(": <");
            builder.append(prefix.getValue());
            builder.append(">\n");
        }
    }
    builder.append(query);

    fullQuery = builder.toString();

    if (prettyPrint || rewriteAndPrint) {
        try {
            EngineConfig config = rewriteAndPrint ? new MockEngineConfig(null) : new ParseOnlyEngineConfig();
            QueryController qc = new Engine(config).prepareQuery(null, fullQuery);
            //StringBuilder outputBuilder = new StringBuilder();
            //qc.prettyPrint(outputBuilder);
            System.out
                    .println(qc.prettyPrintQueryString(EnumSet.of(QueryStringPrintOptions.GENERATE_NEW_PREFIXES,
                            QueryStringPrintOptions.INDENT, QueryStringPrintOptions.USE_PREFIXES,
                            QueryStringPrintOptions.REMOVE_UNUSED_PREFIXES)));
        } catch (ParseException e) {
            // hack, create an anzo exception from the parse exception since we know how to render that
            prettyPrintGlitterParseError(context, fullQuery,
                    new AnzoException(ExceptionConstants.GLITTER.PARSE_EXCEPTION, e, query, e.getMessage()),
                    hiddenPrefixCount);
            throw new CommandException(e, "query");
        }
        return 0;
    }
    if (datasetInput != null) {
        Reader inputDatasetStream = datasetInput.getReader();
        RDFFormat datasetFileFormat = datasetInput.getFormat();

        Dataset dataset = new Dataset();

        try {
            if (!datasetFileFormat.supportsNamedGraphs()) {
                INamedGraph namedGraph = dataset.addDefaultGraph(CommandContext.defaultNamedGraph);
                ReadWriteUtils.loadGraph(namedGraph, inputDatasetStream, datasetFileFormat,
                        ObjectUtils.toString(base));
                queryResults = dataset.executeQuery(Collections.singleton(CommandContext.defaultNamedGraph),
                        null, null, fullQuery, null);
            } else {
                ReadWriteUtils.loadQuadStore(dataset, inputDatasetStream, datasetFileFormat,
                        ObjectUtils.toString(base));
                DefaultQueryDataset queryDataset = new DefaultQueryDataset(
                        allDefaultGraphs ? dataset.getDefaultGraphUris() : null,
                        allNamedGraphs ? dataset.getNamedGraphUris() : null);
                queryResults = new Engine(new QuadStoreEngineConfig(dataset)).executeQuery(null, fullQuery,
                        queryDataset, null);
            }

        } catch (ParseException e) {
            // hack, create an anzo exception from the parse exception since we know how to render that
            prettyPrintGlitterParseError(context, fullQuery,
                    new AnzoException(ExceptionConstants.GLITTER.PARSE_EXCEPTION, e, query, e.getMessage()),
                    hiddenPrefixCount);
            throw new CommandException("query failed");
        }
    } else {
        boolean owns = false;
        try {
            owns = !client.isConnected();
            if (owns) {
                client.connect();
                printOnConnectionSuccess(context);
            }
            long start = 0;
            if (queryTime) {
                start = System.currentTimeMillis();
            }

            Map<String, Object> options = new HashMap<String, Object>();

            if (datasource != null) {
                options.put(OPTIONS.DATASOURCE, datasource);
            }
            if (skipCache) {
                options.put(OPTIONS.SKIPCACHE, Boolean.TRUE);
            }
            if (true) {
                options.put(OPTIONS.INCLUDEMETADATAGRAPHS, Boolean.TRUE);
            }
            Set<URI> defaultGraphs = null;
            if (allDefaultGraphs || allMetadataDefaultGraphs) {
                defaultGraphs = new HashSet<URI>();
                if (allDefaultGraphs) {
                    defaultGraphs.add(GRAPHS.ALL_NAMEDGRAPHS);
                }
                if (allMetadataDefaultGraphs) {
                    defaultGraphs.add(GRAPHS.ALL_METADATAGRAPHS);
                }
            }

            Set<URI> namedGraphs = null;
            if (allNamedGraphs || allMetadataNamedGraphs) {
                namedGraphs = new HashSet<URI>();
                if (allNamedGraphs) {
                    namedGraphs.add(GRAPHS.ALL_NAMEDGRAPHS);
                }
                if (allMetadataNamedGraphs) {
                    namedGraphs.add(GRAPHS.ALL_METADATAGRAPHS);
                }
            }

            queryResults = client.serverQuery(defaultGraphs, namedGraphs, null, fullQuery, null, options);

            if (queryTime) {
                context.writeOutput("server query time (ms): " + (System.currentTimeMillis() - start));
            }
        } catch (AnzoException e) {
            if (e.getErrorCode() == ExceptionConstants.GLITTER.PARSE_EXCEPTION) {
                prettyPrintGlitterParseError(context, fullQuery, e, hiddenPrefixCount);
                throw new CommandException("query failed");
            }
            throw new CommandException(e, "query failed");
        } finally {
            try {
                if (owns)
                    client.close();
            } catch (AnzoRuntimeException e) {
                log.error("Error closing connection", e);
            }
        }
    }
    try {
        if (queryResults.isConstructResult() || queryResults.isDescribeResult()) {
            Collection<Statement> resultSet = (queryResults.isConstructResult())
                    ? queryResults.getConstructResults()
                    : queryResults.getDescribeResults();
            Dataset dataset = new Dataset();

            // anzo datasets are not expressive enough to serialize out a default graph to TriG properly.
            // so populateDataset and outputRdf hack their way around the problem.
            context.populateDataset(dataset, resultSet);
            context.outputRdf(dataset, outputFormat);
        } else {

            OutputStreamWriter writer = new OutputStreamWriter(System.out, "UTF-8");

            if (outputFormat.equals(RDFFormat.SPARQL)) {
                CommonSerializationUtils.writeQueryResults(queryResults, writer,
                        RDFFormat.SPARQL.getDefaultMIMEType());
            } else {
                if (queryResults.isAskResult()) {
                    System.out.println(queryResults.getAskResults());
                } else {
                    SolutionTextWriter.write(context, queryResults.getSelectResults());
                }
            }

            writer.flush();
        }

    } catch (IOException e) {
        throw new CommandException(e, "query");
    }
    return 0;
}

From source file:org.openanzo.client.cli.RdfUploadCommand.java

/**
 * Performs the commit operation.//from  w ww.  j  a v a2  s  .c  o m
 * 
 * Reads through the provided files, constructs diffs by computing the differences between the file and the server graphs and commits those diffs in a
 * transaction to the repository.
 * 
 * @throws AnzoException
 */
protected int update(CommandLine cl, CommandContext context, AnzoClient client,
        Collection<RdfInputArgument> inputs, URI defaultNamedGraphUri, URI base, boolean nonRevisioned)
        throws AnzoException {

    IDataset store = new Dataset();
    INamedGraph defaultNamedGraph = null;

    if (defaultNamedGraphUri == null && inputs.size() == 1) {
        defaultNamedGraphUri = inputs.iterator().next().getDefaultGraphURI();
    }
    if (defaultNamedGraphUri != null) {
        store.addNamedGraph(defaultNamedGraphUri);
        defaultNamedGraph = store.getNamedGraph(defaultNamedGraphUri);
    }

    for (RdfInputArgument input : inputs) {
        try {
            Reader in = input.getReader();
            RDFFormat fileFormat = input.getFormat();

            URI inputBase = base;
            if (inputBase == null) {
                inputBase = input.getDefaultGraphURI();
            }
            if (fileFormat == null) {
                throw new InvalidArgumentException(input.inputName
                        + " is not a valid RDF format file type. Use a proper file type or STDIN.");
            }
            if (!fileFormat.supportsNamedGraphs()) {
                INamedGraph inputNamedGraph = defaultNamedGraph;
                if (inputNamedGraph == null) {
                    URI uri = input.getDefaultGraphURI();
                    if (uri != null) {
                        store.addNamedGraph(uri);
                        inputNamedGraph = store.getNamedGraph(uri);
                    }
                }

                if (defaultNamedGraphUri == null) {
                    throw new InvalidArgumentException(GRAPH.getLongOpt() + " option must be set for format "
                            + fileFormat + " since this format does not support named graphs");
                }
                ReadWriteUtils.loadGraph(inputNamedGraph, in, fileFormat, ObjectUtils.toString(inputBase));
            } else {
                ReadWriteUtils.loadQuadStore(store, in, fileFormat, ObjectUtils.toString(inputBase));
            }
        } catch (AnzoException e) {
            context.writeError("Error loading RDF Input: " + input.inputName);
            throw e;
        }

    }
    return update(cl, context, client, store, base, nonRevisioned);
}

From source file:org.openanzo.client.cli.UnionCommand.java

public int union(CommandContext context, AnzoClient client, Collection<RdfInputArgument> inputs,
        RDFFormat outputFormat, URI defaultNamedGraphUri, URI base) throws AnzoException {
    IDataset store = new Dataset();
    INamedGraph defaultNamedGraph = null;

    if (defaultNamedGraphUri == null && inputs.size() == 1) {
        defaultNamedGraphUri = inputs.iterator().next().getDefaultGraphURI();
    }/* w w w .ja va 2 s  . com*/

    if (defaultNamedGraphUri != null) {
        store.addNamedGraph(defaultNamedGraphUri);
        defaultNamedGraph = store.getNamedGraph(defaultNamedGraphUri);
    }

    for (RdfInputArgument input : inputs) {
        Reader in = input.getReader();
        RDFFormat fileFormat = input.getFormat();

        URI inputBase = base;
        if (inputBase == null) {
            inputBase = input.getDefaultGraphURI();
        }
        if (!fileFormat.supportsNamedGraphs()) {

            INamedGraph inputNamedGraph = defaultNamedGraph;
            if (inputNamedGraph == null) {
                URI uri = input.getDefaultGraphURI();
                if (uri != null) {
                    store.addNamedGraph(uri);
                    inputNamedGraph = store.getNamedGraph(uri);
                }
            }

            if (inputNamedGraph == null) {
                throw new InvalidArgumentException(GRAPH.getLongOpt() + " option must be set for format "
                        + fileFormat + " since this format does not support named graphs");
            }
            ReadWriteUtils.loadGraph(inputNamedGraph, in, fileFormat, ObjectUtils.toString(inputBase));
        } else {
            ReadWriteUtils.loadQuadStore(store, in, fileFormat, ObjectUtils.toString(inputBase));
        }

    }
    context.outputRdf(store, outputFormat);
    return 0;
}

From source file:org.openanzo.client.cli.UpdateCommand.java

public int update(CommandContext context, AnzoClient client, RdfInputArgument add, RdfInputArgument remove,
        URI defaultNamedGraphUri, URI base) throws AnzoException {
    int result = 1;

    IDataset adds = new Dataset();
    IDataset removes = new Dataset();

    INamedGraph addsDefaultNamedGraph = null;
    INamedGraph removesDefaultNamedGraph = null;

    URI addDefaultNamedGraphUri = defaultNamedGraphUri;
    if (addDefaultNamedGraphUri == null && add != null) {
        addDefaultNamedGraphUri = add.getDefaultGraphURI();
    }/*w  ww.j  a  v  a 2s . co  m*/

    URI removeDefaultNamedGraphUri = defaultNamedGraphUri;
    if (removeDefaultNamedGraphUri == null && remove != null) {
        removeDefaultNamedGraphUri = remove.getDefaultGraphURI();
    }

    if (addDefaultNamedGraphUri != null) {
        adds.addNamedGraph(addDefaultNamedGraphUri);
        addsDefaultNamedGraph = adds.getNamedGraph(addDefaultNamedGraphUri);
    }
    if (removeDefaultNamedGraphUri != null) {
        removes.addNamedGraph(removeDefaultNamedGraphUri);
        removesDefaultNamedGraph = removes.getNamedGraph(removeDefaultNamedGraphUri);
    }

    if (add != null) {
        URI addBase = base;
        if (addBase == null) {
            addBase = add.getDefaultGraphURI();
        }
        RDFFormat addFileFormat = add.getFormat();
        if (addFileFormat == null) {
            throw new InvalidArgumentException(
                    add.inputName + " is not a valid RDF format file type. Use a proper file type or STDIN.");
        }
        if (!addFileFormat.supportsNamedGraphs()) {

            if (addDefaultNamedGraphUri == null) {
                throw new InvalidArgumentException(GRAPH.getLongOpt() + " option must be set for format "
                        + addFileFormat + " since this format does not support named graphs");
            }
            ReadWriteUtils.loadGraph(addsDefaultNamedGraph, add.getReader(), addFileFormat,
                    ObjectUtils.toString(addBase));
        } else {
            ReadWriteUtils.loadQuadStore(adds, add.getReader(), addFileFormat, ObjectUtils.toString(addBase));
        }
    }

    if (remove != null) {
        URI removeBase = base;
        if (removeBase == null) {
            removeBase = remove.getDefaultGraphURI();
        }
        RDFFormat removeFileFormat = remove.getFormat();
        if (removeFileFormat == null) {
            throw new InvalidArgumentException(remove.inputName
                    + " is not a valid RDF format file type. Use a proper file type or STDIN.");
        }
        if (!removeFileFormat.supportsNamedGraphs()) {
            if (removeDefaultNamedGraphUri == null) {
                throw new InvalidArgumentException(GRAPH.getLongOpt() + " option must be set for format "
                        + removeFileFormat + " since this format does not support named graphs");
            }
            ReadWriteUtils.loadGraph(removesDefaultNamedGraph, remove.getReader(), removeFileFormat,
                    ObjectUtils.toString(removeBase));
        } else {
            ReadWriteUtils.loadQuadStore(removes, remove.getReader(), removeFileFormat,
                    ObjectUtils.toString(removeBase));
        }
    }

    boolean owns = false;
    try {
        owns = !client.isConnected();
        if (owns) {
            client.connect();
            printOnConnectionSuccess(context);
        }
        client.begin();
        int total = 0;
        for (URI uri : removes.getNamedGraphUris()) {
            ClientGraph graph;
            INamedGraph ng;

            if (UriGenerator.isMetadataGraphUri(uri)) {
                URI uri_ng = UriGenerator.stripEncapsulatedURI(Constants.NAMESPACES.METADATAGRAPH_PREFIX, uri);
                graph = client.getReplicaGraph(uri_ng, getNamedGraphInitializers());
                ng = graph.getMetadataGraph();
                total += removes.getNamedGraph(uri).getStatements().size();
                ng.remove(removes.getNamedGraph(uri).getStatements()); // remove the listed statements from the metadata graph
            } else {
                graph = client.getReplicaGraph(uri, getNamedGraphInitializers());
                ng = removes.getNamedGraph(uri);
                total += ng.getStatements().size();
                graph.remove(ng.getStatements());
            }
            if (total > 20000) {
                client.commit();
                client.begin();
                total = 0;
            }
        }
        for (URI uri : adds.getNamedGraphUris()) {
            ClientGraph graph;
            INamedGraph ng;

            if (UriGenerator.isMetadataGraphUri(uri)) {
                // get the uri of the named graph that is associated with this metadata
                URI uri_ng = UriGenerator.stripEncapsulatedURI(Constants.NAMESPACES.METADATAGRAPH_PREFIX, uri);
                graph = client.getReplicaGraph(uri_ng, getNamedGraphInitializers()); // get the named graph object
                ng = graph.getMetadataGraph();
                total += adds.getNamedGraph(uri).getStatements().size();
                ng.add(adds.getNamedGraph(uri).getStatements()); // add the new statements to the metadata graph
            } else {
                graph = client.getReplicaGraph(uri, getNamedGraphInitializers());
                ng = adds.getNamedGraph(uri);
                total += ng.getStatements().size();
                graph.add(ng.getStatements());
            }
            if (total > 20000) {
                client.commit();
                client.begin();
            }
        }
        client.commit();
        client.updateRepository();
        result = 0;
    } catch (UpdateServerException e) {
        context.writeError("Update failed due to validation error(s): ");
        for (List<AnzoException> list : e.getErrors()) {
            for (AnzoException ex : list) {
                if (ex.getErrorCode() == ExceptionConstants.VALIDATION.INVALID_TYPEDLITERAL_LABEL) {
                    context.writeError("\t" + ex.getArgs()[0]);
                } else {
                    context.writeError("unknown transaction error:" + ex.getMessage(false));
                    context.getConsoleWriter().printException(ex, context.getShowTrace());
                }
            }
        }
    } finally {
        try {
            if (owns)
                client.close();
        } catch (AnzoRuntimeException e) {
            log.error("Error closing connection", e);
        }
    }
    return result;
}

From source file:org.openanzo.rdf.MemValueFactory.java

@Override
public Statement createStatement(Resource subj, URI prop, Value obj) {
    if (subj == null || prop == null || obj == null)
        throw new AnzoRuntimeException(ExceptionConstants.CLIENT.NO_NULL_VALUES, ObjectUtils.toString(subj),
                ObjectUtils.toString(prop), ObjectUtils.toString(obj));
    return new Statement(subj, prop, obj);
}

From source file:org.openanzo.rdf.MemValueFactory.java

@Override
public Statement createStatement(Resource subj, URI prop, Value obj, URI namedGraphUri) {
    if (subj == null || prop == null || obj == null || namedGraphUri == null)
        throw new AnzoRuntimeException(ExceptionConstants.CLIENT.NO_NULL_VALUES,
                ObjectUtils.toString(namedGraphUri), ObjectUtils.toString(subj), ObjectUtils.toString(prop),
                ObjectUtils.toString(obj));
    return new Statement(subj, prop, obj, namedGraphUri);
}

From source file:org.openehr.adl.am.AmObjectFactory.java

public static ExprLeaf newExprLeaf(String type, RmTypes.ReferenceType referenceType, Object value) {
    ExprLeaf result = new ExprLeaf();
    result.setType(type);/* w  ww. j  a va  2  s  .  c om*/
    result.setReferenceType(ObjectUtils.toString(referenceType));
    result.setItem(value);
    return result;
}

From source file:org.openhab.action.openwebif.internal.impl.model.adapter.BooleanTypeAdapter.java

/**
 * {@inheritDoc}//from  w  w w  .  j  a v  a2 s  .c  o m
 */
@Override
public Boolean unmarshal(String value) throws Exception {
    return Boolean.parseBoolean(StringUtils.trim(ObjectUtils.toString(value)));
}